Train Problem II 卡特兰数

本文探讨了给定火车入站顺序的情况下,所有可能的出站顺序数量问题。通过使用卡特兰数的数学概念,文章提供了一种有效的方法来计算特定数量的火车可能的出站顺序总数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Train Problem II

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


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 
 

Statistic | Submit | Discuss | Note

题目类似于出栈问题

一个栈(无穷大)的进栈序列为1,2,3,…,n,有多少个不同的出栈序列?

首先,我们设f(n)=序列个数为n的出栈序列种数。(我们假定,最后出栈的元素为k,显然,k取不同值时的情况是相互独立的,也就是求出每种k最后出栈的情况数后可用加法原则,由于k最后出栈,因此,在k入栈之前,比k小的值均出栈,此处情况有f(k-1)种,而之后比k大的值入栈,且都在k之前出栈,因此有f(n-k)种方式,由于比k小和比k大的值入栈出栈情况是相互独立的,此处可用乘法原则,f(n-k)*f(k-1)种,求和便是Catalan递归式。

首次出空之前第一个出栈的序数k将1~n的序列分成两个序列,其中一个是1~k-1,序列个数为k-1,另外一个是k+1~n,序列个数是n-k。
此时,我们若把k视为确定一个序数,那么根据 乘法原理,f(n)的问题就等价于——序列个数为k-1的出栈序列种数乘以序列个数为n - k的出栈序列种数,即选择k这个序数的f(n)=f(k-1)×f(n-k)。而k可以选1到n,所以再根据 加法原理,将k取不同值的序列种数相加,得到的总序列种数为:f(n)=f(0)f(n-1)+f(1)f(n-2)+……+f(n-1)f(0)。
看到此处,再看看卡特兰数的递推式,答案不言而喻,即为f(n)=h(n)= C(2n,n)/(n+1)= c(2n,n)-c(2n,n-1)(n=0,1,2,……)。
最后,令f(0)=1,f(1)=1。


递推公式::

h(n) = h(n - 1) * (4 * n - 2) /( n+ 1)

import java.util.Scanner;
import java.math.*;
public class Main {
public static void main(String args[]){
	    int n;
	   Scanner scan=new Scanner(System.in);
	   BigInteger f[]=new BigInteger[101];
	   f[0]=BigInteger.ONE;
	   f[1]=BigInteger.ONE;
	   for(int i=2;i<=100;i++)
	   {
		   f[i]=f[i-1].multiply(BigInteger.valueOf(4).multiply(BigInteger.valueOf(i)).subtract(BigInteger.valueOf(2))).divide(BigInteger.valueOf(i+1));
                  //这一句其实是可以简单写的
                  // f[i]=f[i-1].multiply(BigInteger.valueOf(4*i-2)).divide(BigInteger.valueOf(i+1));
           }
	   while(scan.hasNext())
	   {
		   n=scan.nextInt();
		   System.out.println(f[n]);
	   }
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值