hdu 1023 Train Problem II (catalan數)

Train Problem II

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


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.
 
這個題目,由於我們上課講過,所以想都沒想,就知道是catalan數,想到這個之後,這個題目就變成了高精度了。
關於catalan數的一些經典的應用,可以看看這個:http://baike.baidu.com/view/2499752.htm

下面是用java過的:
import java.util.*;
import java.math.BigInteger;

public class Main {

    public static void main(String[] args) {
        
        BigInteger[] a = new BigInteger[110];
        a[0] = BigInteger.ONE;
        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 n;
        while(in.hasNext())
        {
            n = in.nextInt();
            System.out.println(a[n]);
        }
    }
}

可以用作模板的代碼:
//*******************************
//打表卡特蘭數
//第 n個 卡特蘭數存在a[n]中,a[n][0]表示長度;
//注意數是倒着存的,個位是 a[n][1] 輸出時注意倒過來。
//*********************************
#include<cstdio>
using namespace std;
int a[110][300];
int n;
void catalan()
{
    a[1][0]=1;
    a[1][1]=1;
    a[2][0]=1;
    a[2][1]=2;
    for(int i=3;i<=100;i++)
    {
        int len=a[i-1][0];
        int carry=0;
        for(int j=1;j<=len;j++)//進行乘法
        {
            int temp=a[i-1][j]*(4*i-2)+carry;
            carry=temp/10;
            a[i][j]=temp%10;
        }
        while(carry)//處理餘數
        {
            a[i][++len]=carry%10;
            carry/=10;
        }
        for(int j=len;j>=1;j--)//進行除法
        {
            int temp=a[i][j];
            a[i][j]=(temp+carry*10)/(i+1);
            carry=(temp+carry*10)%(i+1);
        }
        while(!a[i][len])len--;//消去前導零
        a[i][0]=len;
    }
}
int main()
{
    catalan();
    while(~scanf("%d",&n))
    {
        for(int i=a[n][0];i>=1;i--)
            printf("%d",a[n][i]);
        printf("\n");
    }
    return 0;
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章