Count the Trees Problem Description Another common social inability is known as ACM (Abnormally Compulsive Meditation). This psychological disorder is somewhat common among programmers. It can be described as the temporary (although frequent) loss of the faculty of speech when the whole power of the brain is applied to something extremely interesting or challenging. 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 The input will consist of several input cases, one per line. Each input case will be specified by the number n ( 1 ≤ n ≤ 100 ) of different elements that must be used to form the trees. A number 0 will mark the end of input and is not to be processed. Output For each input case print the number of binary trees that can be built using the n elements, followed by a newline character. Sample Input 1 2 10 25 0 Sample Output 1 4 60949324800 75414671852339208296275849248768000000 Source UVA Recommend Eddy 下面發代碼吧! [cpp] //典型的卡特蘭數的應用 //判定二叉樹的數量!假設有n個節點,一共有h(n)種數 //可以這樣考慮:先選定一個節點為根節點,則還余下n-1個節點 //如果根節點左子樹無節點,則右子樹有n-1個節點 //如果左子樹有1個節點,則右子樹有n-2個節點~~~ //因此一共的種數是h(n)=h(0)*h(n-1)+h(1)*h(n-1)+~~~+h(n-1)*h(0) //而這恰好是卡特蘭數的表達式!卡特蘭數一般的表達式為h(n)=(2*n)!/[(n+1)!*n!] (n>=2) #include<iostream> using namespace std; #define MAX 101 #define BASE 10000 void multiply(int a[],int len,int b) { for(int i=len-1,carry=0;i>=0;--i) { carry=carry+b*a[i]; a[i]=carry%BASE; carry=carry/BASE; } } void divide(int a[],int len,int b) { for(int i=0,div=0;i<len;i++) { div=div*BASE+a[i]; a[i]=div/b; div=div%b; } } int main() { int i,j,h[101][MAX]; int a[MAX]; memset(h[1],0,MAX*sizeof(int)); for(i=2,h[1][MAX-1]=1;i<=100;i++) { memcpy(h[i],h[i-1],MAX*sizeof(int)); multiply(h[i],MAX,4*i-2); divide(h[i],MAX,i+1); } while(cin>>i && i>=1 && i<=100) { memcpy(a,h[i],MAX*sizeof(int)); for(j=2;j<=i;j++) multiply(a,MAX,j); for(j=0;j<MAX && a[j]==0;j++); printf("%d",a[j++]); for(;j<MAX;j++) printf("%04d",a[j]); printf("\n"); } return 0; }