Train Problem II
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 12037 Accepted Submission(s): 6424
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
题意:就是有一个火车站,有一个进站时间表,然后问你合法的进出站(栈)数有多少种。
题解:既然要出站,那么必须得有火车在站(栈)里面,我们把进站(栈)想象成左括号,出站(栈)想象成右括号。就是求合法的括号序列,很明显是一个Catalan数,但是由于数据过大,递推在35左右就爆 long long ,所以不能直接递推,我们利用Catalan数的递推式来模拟乘除法。卡特兰数递推式 :catalan(n) = catalan(n-1)*(4*n-2)/(n+1)
#include<cstdio>
using namespace std;
const int maxn=101;
int a[maxn][maxn],b[maxn];
void catalan() //卡特兰数 递推式 catalan(n) = catalan(n-1)*(4*n-2)/(n+1)
{
int carry,temp,len;
a[1][0] = b[1] = 1;
len = 1;
for(int i = 2; i <= 100; i++){
for(int j = 0; j < len; j++){ //递推式 乘法
a[i][j]=a[i-1][j]*(4*(i-1)+2);
}
carry=0;
for(int 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(int 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--; // 去掉高位0
b[i] = len;
}
return ;
}
int main()
{
catalan();
int n;
while(scanf("%d",&n)==1){
for(int i = b[n]-1; i >= 0; i--) printf("%d",a[n][i]);
printf("\n");
}
return 0;
}