Train Problem II
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 7977 Accepted Submission(s): 4278
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
Hint
The result will be very large, so you may not process it by 32-bit integers.
Author
Ignatius.L
Recommend
We have carefully selected several similar problems for you: 1133 1022 1130 1131 1134
题意:从1~n的n个数依次进栈,问共有多少种出栈方式。
题解:有n个位置,现在任意选定一个数,比如1,那么1可以在1–>n的任意一个位置上。假设1在第k的位置上,显然在1的前面有k-1个数,并且这些数的数值为2–>k,在1后面有n-k个数。用f(k)表示k个数顺序入栈后的出栈顺序,则f(n)就是我们要求的最终答案。而f(n)这个事件又可以分解成1在1–>n这n个位置上出现的n种情况,于是根据加法/乘法原理,易得f(n)是卡特兰数.
但本题还有一个问题,就是会爆long long,要用高精度存。所以我是用了java。
Java使用方法详见收藏夹。
Java代码如下:
import java.util.*;
import java.math.*;
public class Main {
public static void main(String[] args) {
BigInteger[] f = new BigInteger[100+10];
f[1] = BigInteger.valueOf(0);
f[2] = BigInteger.valueOf(1);
f[3] = BigInteger.valueOf(1);
for(int i = 3;i <= 103;i++){
long temp = 4 * i - 6;
BigInteger T = new BigInteger(String.valueOf(0));
T = BigInteger.valueOf(temp);
f[i+1] = f[i].multiply(T);
T = BigInteger.valueOf(i);
f[i+1] = f[i+1].divide(T);
}
Scanner cin = new Scanner(System.in);
while(cin.hasNext()){
int n = cin.nextInt();
System.out.println(f[n+2]);
}
}
}
另注:卡特兰数中f[2]=f[3]=1,f[4]=2,f[5]=5。。。,并不是从一开始的,做本题时要错2位输出。