Train Problem II
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 9019 Accepted Submission(s): 4829
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
大致题意:
进出火车站的轨道只有一条,但火车站内可以停无数的火车。求问n列火车全部进、出站的方法数。
实际上火车站相当于一个栈,每个火车就是一个元素。
大体思路:
这个题就是卡特兰数的应用。
首先假定第k辆车最后出栈,f(k) = f(k-1) + f(n+1-k) 。k可以取1到n。由此符合卡特兰数的特点。
卡特兰数的递推公式为:
h(n)= h(0)*h(n-1)+h(1)*h(n-2) + ... + h(n-1)*h(0) (n>=2)
h(n)=h(n-1)*(4*n-2)/(n+1);
h(n)=C(2n,n)/(n+1) (n=0,1,2,...)
h(n)=c(2n,n)-c(2n,n-1)(n=0,1,2,...)
#include<cstdio>
int Table[101][30];
int Len[101];
int N;
void GetTable ()
{
Table[0][0]=Len[0]=1;
for(int t=1;t<=100;t++){
Table[t][0]=1,Len[t]=Len[t-1];
for(int i=0;i<Len[t];i++)
Table[t][i]=Table[t-1][i]*(4*t-2);
for(int i=Len[t]-1,k=0,m=0;i>=0;i--)
k=(1000*m+Table[t][i])%(t+1),Table[t][i]=(1000*m+Table[t][i])/(t+1),m=k;
for(int i=0;i<Len[t];i++)
if(Table[t][i]>999){
Table[t][i+1]+=Table[t][i]/1000,Table[t][i]%=1000;
if(i==Len[t]-1) Len[t]++;
}
}
}
int main()
{
//freopen("in.txt","r",stdin);
GetTable();
while(scanf("%d",&N)!=EOF){
printf("%d",Table[N][Len[N]-1]);
for(int i=Len[N]-2;i>=0;i--)
printf("%03d",Table[N][i]);
printf("\n");
}
return 0;
}