Train Problem II

转载于:http://m.blog.csdn.net/blog/u011471397/11648721#

Train Problem II

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


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
 
 
 
 
这是一道卡特兰数的题目,我觉得还不错,我一开始想要用递推按照递推的式子把它推出来的,long long int
 
不过现在觉得真的好搞笑,因为50 就已经不行了,所以我们要用一个模拟的方法把它做出来才行,这个模板实
 
在是经典的,很不错啊。
 
 
为什么要用卡特兰数呢?
 
首先,我们设f(n)=序列个数为n的出栈序列种数。同时,我们假定,从开始到栈第一次出到空为止,这 段过程中出栈的序数最大的是k。特别地,如果栈直到整个过程结束时才空,则k=n
首次出空之前第一个出栈的序数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。
 
 
我仔细看了百度全科的这段话,说的很对。
 
 
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int a[120][122];
int b[130];
int i,j,k,n;
void  catalan()
{
    int tem,len;
    a[1][0]=1;
    a[1][1]=1;
    a[2][0]=1;
    a[2][1]=2;
    len=1;
    for(i=3;i<=100;i++)
    {

       tem=0;
       for(j=1;j<=len;j++)
       {
          k=a[i-1][j]*(4*i-2)+tem;
          tem=k/10;
          a[i][j]=k%10;
       }
       while(tem)
       {
           len++;
           a[i][len]=tem%10;
           tem=tem/10;
       }
       for(j=len;j>=1;j--)
       {
           k=a[i][j]+tem*10;
           a[i][j]=k/(i+1);
           tem=k%(i+1);
       }
       while(!a[i][len])
       {
           len--;
       }
       a[i][0]=len;
    }
}
int main()
{

    catalan();
    while(scanf("%d",&n)!=EOF)
    {

        /*for(i=4;i<=n;i++)//h(n)=h(n-1)*(4*n-2)/(n+1);
        {
            //a[i]=a[i-1]*(4*i-2)/(n+1);
            //printf("%lld  %d\n",a[i],i);
            //h[i] = h[i-1] * (4*i-2) / (i+1) ;
        }
        printf("%lld\n",h[n]);*/
        for(i=a[n][0];i>=1;i--)
        {
            printf("%d",a[n][i]);
        }
        printf("\n");


    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值