Train Problem II(卡特蘭數)

来源:互联网 发布:郑秀晶崔雪莉关系知乎 编辑:程序博客网 时间:2024/06/07 12:10

Time Limit : 2000/1000ms (Java/Other) Memory Limit : 65536/32768K (Java/Other)

Problem Description

As we all know the Train Problem I, the boss of the Ignatius Train Station want to know if all the trains come in strict-increasing order, how many orders that all the trains can get out of the railway.

Input

The input contains several test cases. Each test cases consists of a number N(1<=N<=100). The input is terminated by the end of file.

Output

For each test case, you should output how many ways that all the trains can get out of the railway.

Sample Input

1
2
3
10

Sample Output

1
2
5
16796

Hint

The result will be very large, so you may not process it by 32-bit integers.

Author

Ignatius.L

卡特蘭數公式+大數算法

#include<iostream>#include<cstring>using namespace std;#define maxn 120int a[maxn][maxn];//儲存卡特蘭數int b[maxn];//n對應卡特蘭數的長度void Catalan()//卡特蘭數計算函數{    //計算公式:h(n)=h(n-1)*(4*n-2)/(n+1);    //大數運算    int i, j, len, carry, temp;    a[1][0] = b[1] = 1;    a[0][0] = 0;    len = 1;    for (i = 2; i <= 100; i++)    {        for (j = 0; j < len; j++)//len 始終等於前一個卡特蘭數的位數        {            a[i][j] = a[i - 1][j] * (4 * (i - 1) + 2);        }        carry = 0;        for (j = 0; j < len; j++)//進位操作        {            temp = a[i][j] + carry;            a[i][j] = temp % 10;            carry = temp / 10;        }        while (carry)        {            a[i][len++] = carry % 10;            carry /= 10;        }        carry = 0;        for (j = len - 1; j >=0; j--)//除法        {            temp = carry * 10 + a[i][j];            a[i][j] = temp / (i + 1);            carry = temp % (i + 1);        }        while (!a[i][len - 1])            len--;        b[i] = len;    }}int main(){    int n;    Catalan();//打表    while (~scanf("%d", &n))    {        for (int k = b[n]-1; k >=0; k--)        {            printf("%d",a[n][k]);        }        printf("\n");    }    return 0;}
原创粉丝点击