Train Problem II
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 5295 Accepted Submission(s): 2869
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 16796HintThe result will be very large, so you may not process it by 32-bit integers.
这个题目,由于我们上课讲过,所以想都没想,就知道是catalan数,想到这个之后,这个题目就变成了高精度了。
关于catalan数的一些经典的应用,可以看看这个:
http://baike.baidu.com/view/2499752.htm
下面是用java过的:
import java.util.*;
import java.math.BigInteger;
public class Main {
public static void main(String[] args) {
BigInteger[] a = new BigInteger[110];
a[0] = BigInteger.ONE;
a[1] = BigInteger.valueOf(1);
for(int i =2;i <= 100; i++)
{
a[i] = a[i-1].multiply(BigInteger.valueOf(4 * i -2)).divide(BigInteger.valueOf(i + 1));
}
Scanner in = new Scanner(System.in);
int n;
while(in.hasNext())
{
n = in.nextInt();
System.out.println(a[n]);
}
}
}
//*******************************
//打表卡特兰数
//第 n个 卡特兰数存在a[n]中,a[n][0]表示长度;
//注意数是倒着存的,个位是 a[n][1] 输出时注意倒过来。
//*********************************
#include<cstdio>
using namespace std;
int a[110][300];
int n;
void catalan()
{
a[1][0]=1;
a[1][1]=1;
a[2][0]=1;
a[2][1]=2;
for(int i=3;i<=100;i++)
{
int len=a[i-1][0];
int carry=0;
for(int j=1;j<=len;j++)//进行乘法
{
int temp=a[i-1][j]*(4*i-2)+carry;
carry=temp/10;
a[i][j]=temp%10;
}
while(carry)//处理余数
{
a[i][++len]=carry%10;
carry/=10;
}
for(int j=len;j>=1;j--)//进行除法
{
int temp=a[i][j];
a[i][j]=(temp+carry*10)/(i+1);
carry=(temp+carry*10)%(i+1);
}
while(!a[i][len])len--;//消去前导零
a[i][0]=len;
}
}
int main()
{
catalan();
while(~scanf("%d",&n))
{
for(int i=a[n][0];i>=1;i--)
printf("%d",a[n][i]);
printf("\n");
}
return 0;
}