hdu 1023 Train Problem II(java+卡特兰数)

来源:互联网 发布:mac内置麦克风没声音 编辑:程序博客网 时间:2024/05/28 20:20

Train Problem II

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 6442    Accepted Submission(s): 3505


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
12310
 

Sample Output
12516796
Hint
The result will be very large, so you may not process it by 32-bit integers.
 

Author
Ignatius.L
题目分析:给出了n个火车,和他们进站的顺序,问出栈的顺序有多少种,一看就是出栈入栈的问题,很容易想到解决递归问题的卡特兰数,首先我们将进栈状态看成是1,出栈状态看成是0,那么所哟状态的顺序种类是C(2*n,n),然后去除掉非法的状态,也就是状态0比1状态多的情况,也就是在2*m+1位上累计出现了m+1个0,后面的序列中必定还有n-m-1个0和n-m+1个1,如果0和1对换不影响排列种类,所以每个不合法的顺位对应一个n+1个0,和n-1个1的序列,那么sum = c(2*n,n) -c(2*n,n+1),正好是卡特兰数,卡特兰数在解决递归计数问题中有着不可替代的作用
import java.math.BigInteger;import java.util.Scanner;public class Main {    BigInteger [][] c = new BigInteger[202][202];public  void init ( ){c[1][1] = c[1][0] =c[0][0] = BigInteger.ONE; for ( int i = 2 ; i <=  200 ; i++ ) for ( int j = 0 ; j <= i ; j++ ) if ( j == 0 || j == i ) c[i][j] = BigInteger.ONE; else c[i][j] = c[i-1][j-1].add(c[i-1][j]);}public static  void main ( String args[]  ){Main a = new Main ();a.init();Scanner cin = new Scanner ( System.in );while ( cin.hasNext() ){int n = cin.nextInt();System.out.println ( a.c[2*n][n].divide(BigInteger.valueOf(n+1)) );}}}


0 0