Search Here

Saturday, July 25, 2015

UVa - 10223 Solution ( How Many Nodes Solution )[ C & C++ Code ]

=>Try Yourself First. For help Scroll Down .

Clearance : Normally you have the number of Nodes and You had to Find out how many trees you will Form through those Nodes . But Here problem is Reverse . You have the Number of Trees . You have to Find the Number of Nodes . To find the number of Trees from N nodes you have to use The Rules for Catalan Numbers . That is :
C_0 = 1 \quad \mbox{and} \quad C_{n+1}=\frac{2(2n+1)}{n+2}C_n,     Its a Derived DP formula . The Main Formula is Given Below :
C_n = {2n\choose n} - {2n\choose n+1} = {1\over n+1}{2n\choose n} \quad\text{ for }n\ge 0,
As the Maximum Length of input may be 25 . Precalculate all the Catalan Numbers  from 1 to 25 . Then find whether the input is Match with i'th Catalan Numbers  . If it is the Print ' i ' .

Code :

#include<bits/stdc++.h>

using namespace std;

long long int catalan[30];

int solve()
{
    catalan[0]=1;
    int i = 0;
    while(i<25)
    {
        catalan[i+1] = (catalan[i] * (4*i + 2))/(i + 2);
        i++;
    }
}

int main()
{
    solve();
    long long int n;
    while(scanf("%lld",&n)==1)
    {
        for(int i = 1; i<25; i++)
        {
            if(n==catalan[i])
                 { printf("%d\n",i); break; }
        }
    }
    return 0;
}
/*
I have solved this by Catalan Expression's Recurrence Relation
C(n) = (2*(2n+1)/(n+2)) * C(n-1);
Where C0 = 1
*/


=>Question or Need Help ?? Leave a Comment .

No comments:

Post a Comment