1. 程式人生 > >(母函數 Catalan數 大數乘法 大數除法) Train Problem II hdu1023

(母函數 Catalan數 大數乘法 大數除法) Train Problem II hdu1023

seve sample divide ict ins OS hdu aps nbsp

Train Problem II

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)

Total Submission(s): 10372 Accepted Submission(s): 5543

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.

註意:

這是卡特蘭數,用大數。使用的公式為:

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

用JAVA更簡單:

技術分享圖片
import java.math.BigInteger;
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner in = new
Scanner (System.in); BigInteger a[]=new BigInteger[101]; a[0]=BigInteger.ZERO; a[1]=BigInteger.ONE; for(int i=2;i<=100;i++) a[i]=a[i-1].multiply(BigInteger.valueOf(4*i-2)).divide(BigInteger.valueOf(i+1)); while(in.hasNextInt()) { int n=in.nextInt(); System.out.println(a[n]); } } }
View Code

接下來是C++:

技術分享圖片
#include <iostream>
#include <cstdio>
using namespace std;
int a[105][105];
int i,j,n;
void ctl()         //打表。
{
    a[2][0]=1;
    a[2][1]=2;
    a[1][0]=1;
    a[1][1]=1;
    int len=1,t,yu=0;       //註意初始化。
    for(i=3;i<101;i++)         //先打表求出1到100的所有Catalan數。
    {
        for(j=1;j<=len;j++)              //大數乘法。
        {
            t=a[i-1][j]*(4*i-2)+yu;
            yu=t/10;
            a[i][j]=t%10;       //求每位數的確定的數。
        }
        while(yu)         //進位。一直到yu為0為止。
        {
            a[i][++len]=yu%10;
            yu/=10;
        }
        for(j=len;j>=1;j--)              //大數除法。聯系手工除法步驟。
        {
            t=a[i][j]+yu*10;
            a[i][j]=t/(i+1);           //可以看做手工除法的商。
            yu=t%(i+1);              //可以看做手工除法的余數。
        }
        while(!a[i][len])        //去掉前邊的0。
        {
            len--;
        }
        a[i][0]=len;
    }
}
int main()
{
    ctl();
    int n;
    while(~scanf("%d",&n))
    {
        for(int i=a[n][0];i>0;i--)
        {
            printf("%d",a[n][i]);
        }   
        puts("");
    }   
    return 0;
} 
View Code

(母函數 Catalan數 大數乘法 大數除法) Train Problem II hdu1023