Count the Trees
Time Limit : 2000/1000ms (Java/Other) Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 16 Accepted Submission(s) : 14
Font: Times New Roman | Verdana | Georgia
Font Size: ← →
Problem Description
Juan is a very gifted programmer, and has a severe case of ACM (he even participated in an ACM world championship a few months ago). Lately, his loved ones are worried about him, because he has found a new exciting problem to exercise his intellectual powers, and he has been speechless for several weeks now. The problem is the determination of the number of different labeled binary trees that can be built using exactly n different elements.
For example, given one element A, just one binary tree can be formed (using A as the root of the tree). With two elements, A and B, four different binary trees can be created, as shown in the figure.
If you are able to provide a solution for this problem, Juan will be able to talk again, and his friends and family will be forever grateful.
Input
Output
Sample Input
1 2 10 25 0
Sample Output
1
4
60949324800
75414671852339208296275849248768000000
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
#define MAX 100
#define BASE 10000
void multiply(int a[],int Max,int b)
{
int i,array=0;
for(i=Max-1;i>=0;i--)
{
array+=b*a[i];
a[i]=array%BASE;
array/=BASE;
}
}
void divide(int a[],int Max,int b)
{
int i,div=0;
for(i=0;i<Max;i++)
{
div=div*BASE+a[i];
a[i]=div/b;
div%=b;
}
}
int main(int argc, char *argv[])
{
int a[101][MAX],i,j,n;
memset(a[1],0,MAX*sizeof(int));
for(i=2,a[1][MAX-1]=1;i<101;i++)
{
memcpy(a[i],a[i-1],MAX*sizeof(int));
multiply(a[i],MAX,4*i-2);
multiply(a[i],MAX,i);\\这里仅仅多加了一步就可以了,还是比较好来理解的
divide(a[i],MAX,i+1);
}
while(cin>>n)
{
if(n==0) break;
for(i=0;i<MAX&&a[n][i]==0;i++) ;
cout<<a[n][i++];
for(;i<MAX;i++) printf("%04d",a[n][i]);
cout<<endl;
}
return 0;
}