Count the Trees-卡特蘭數\高精度乘法

問題來源:hdu-1131

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

問題大意:輸入結點的個數,問這些結點能組成的不同二叉樹的個數。PS:二叉樹是有向樹,形狀數*n!=二叉樹數。形狀數就是卡特蘭數(也可應用於矩陣連乘和判斷24點的括號情況數),因爲當分支向左邊k條時,向右的分支自然有n-1-k條,即f(n)=f(0)*f(n-1)+f(1)*f(n-2)+...+f(n-1)*f(0)

源代碼:
#include<stdio.h>
#include<string.h>

int  N , len;
int  num[100000];

void mult( int k );

int main( ){

    while( ~scanf_s("%d",&N) && N ){
        memset( num , 0 , sizeof( num ) );
        num[0] = len = 1;
        for( int i=N+2 ; i<=2*N ; i++ )
            mult( i );
        for( int i=len-1 ; i>=0 ; i-- )
            printf("%d",num[i]);
        printf("\n");
    }

    return 0;
}


void mult( int k ){
    for( int i=0 ; i<len ; i++ )
        num[i] *= k;
    for( int i=0 ; i<len ; i++ ){
        if( num[len-1]>=10 )
            len += 1;
        num[i+1] += num[i]/10;
        num[i] %= 10;
    }
}



代碼分析:代碼的目的是求出卡特蘭數,但如果直接採用定義f(n)=f(0)*f(n-1)+f(1)*f(n-2)+...+f(n-1)*f(0)的話時間複雜度O(n)=n^2,所以採用組合數學的知識,知f(n)=C(2*n,n)/(n+1)=(n+2)*(n+3)*...*2n,用例給出了超精度數,則該題也考了高精度乘法。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章