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…
它的一般项公式为:
注意数据量非常大,无法使用基本数据类型,所以需要额外写大数乘法和大数除法。
#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;
}
}