传送门:Train Problem II
Train Problem II
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 5121 Accepted Submission(s): 2762
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.
Author
Ignatius.L
解题报告:
此题为高精度卡特兰数。
1.Catalan数的组合公式为 Cn=C(2n,n) / (n+1);
2.此数的递归公式为 h(n ) = h(n-1)*(4*n-2) / (n+1)。
令h(1)=1,h(0)=1,catalan数满足递归式:
h(n)= h(0)*h(n-1)+h(1)*h(n-2) + ... + h(n-1)h(0) (其中n>=2)
例如:h(2)=h(0)*h(1)+h(1)*h(0)=1*1+1*1=2
h(3)=h(0)*h(2)+h(1)*h(1)+h(2)*h(1)=1*2+1*1+2*1=5
另类递归式:
h(n)=h(n-1)*(4*n-2)/(n+1);
该递推关系的解为:
h(n)=C(2n,n)/(n+1) (n=1,2,3,...)
C语言高精度代码:
#include<stdio.h>
int a[101][101]= {0};
int main(){
int i,j,n,k,b[101],len;
a[1][0]=1;
b[1]=len=1;
for(i=2;i<=100;i++){
for(j=0;j<len;j++) //乘法
a[i][j]=(4*i-2)*a[i-1][j];
for(k=j=0;j<len;j++){
a[i][j]+=k;
k=a[i][j]/10;
a[i][j]%=10;
}
while (k){
a[i][len++]=k%10;
k/=10;
}
for(j=len-1,k=0;j>=0;j--){ //除法
a[i][j]+= k*10;
k=a[i][j]%(i+1);
a[i][j]/=(i+1);
}
while(!a[i][len-1])
len--;
b[i]=len;
}
while(scanf("%d",&n)==1){
for(i=b[n]-1;i>=0;i--)
printf("%d",a[n][i]);
printf("\n");
}
return 0;
}
Java代码:
import java.io.*;
import java.util.*;
import java.math.BigInteger;
public class Main
{
public static void main(String args[])
{
BigInteger[] a = new BigInteger[110];
a[0] = BigInteger.ZERO;
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 t;
while(in.hasNext())
{
t = in.nextInt();
System.out.println(a[t]);
}
}
}