Train Problem II

Train Problem II

Describe
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.

这个序列是卡特兰数列,它的前几项为 1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786, 208012, 742900, 2674440, 9694845, 35357670…
它的一般项公式为:

Hn=1n+1Cn2n=(2n)!(n+1)!n!
递推公式为:
Hn+1=i=0nHiHni=2(2n+1)n+2Hn(n0)

注意数据量非常大,无法使用基本数据类型,所以需要额外写大数乘法和大数除法。

#include<iostream>
#include<cstring>
#include<iomanip>
#define MAX 101
#define BASE 1000000

using namespace std;

void cheng(int i,int n);
void chu(int i,int n);

int ans[MAX][101];

int main()
{
    ans[0][100]=ans[1][100]=1;
    for(int i=2;i<MAX;i++)
    {
        if(i==16)
            ;
        memcpy(ans[i],ans[i-1],sizeof(int)*MAX);
        cheng(i,4*i-2);
        chu(i,i+1);
    }
    int n;
    while(cin>>n)
    {
        int i=0;
        while(!ans[n][i++]);
        cout<<ans[n][i-1];
        for(int j=i;j<=100;j++)
            cout<<setfill('0')<<setw(6)<<ans[n][j];
        cout<<endl;
    }
    return 0;
}

void cheng(int i,int n)
{
    int temp=0;
    for(int j=100;j>=0;j--)
    {
        ans[i][j]*=n;
        ans[i][j]+=temp;
        temp=ans[i][j]/BASE;
        ans[i][j]%=BASE;
    }
}

void chu(int i,int n)
{
    int j=-1,remain=0;
    while(!ans[i][++j]);
    for(;j<=100;j++)
    {
        ans[i][j]+=remain*BASE;
        remain=ans[i][j]%n;
        ans[i][j]/=n;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值