1. 程式人生 > >hdu 1023 ——Train Problem II(卡特蘭數+高精度+java)

hdu 1023 ——Train Problem II(卡特蘭數+高精度+java)

Train Problem II
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 7977 Accepted Submission(s): 4278

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

題意:從1~n的n個數依次進棧,問共有多少種出棧方式。

題解:有n個位置,現在任意選定一個數,比如1,那麼1可以在1–>n的任意一個位置上。假設1在第k的位置上,顯然在1的前面有k-1個數,並且這些數的數值為2–>k,在1後面有n-k個數。用f(k)表示k個數順序入棧後的出棧順序,則f(n)就是我們要求的最終答案。而f(n)這個事件又可以分解成1在1–>n這n個位置上出現的n種情況,於是根據加法/乘法原理,易得f(n)是卡特蘭數.
但本題還有一個問題,就是會爆long long,要用高精度存。所以我是用了java。
Java使用方法詳見收藏夾。

Java程式碼如下:

import java.util.*;
import java.math.*;

public class Main { 
    public static void main(String[] args) { 
        BigInteger[] f = new BigInteger[100+10];
        f[1] = BigInteger.valueOf(0);
        f[2] = BigInteger.valueOf(1);
        f[3] = BigInteger.valueOf(1);
        for(int i = 3;i <= 103;i++){
            long temp = 4 * i - 6;
            BigInteger T = new BigInteger(String.valueOf(0));
            T = BigInteger.valueOf(temp);
            f[i+1] = f[i].multiply(T);
            T = BigInteger.valueOf(i);
            f[i+1] = f[i+1].divide(T);
        }
        Scanner cin = new Scanner(System.in);
        while(cin.hasNext()){
            int n = cin.nextInt();
            System.out.println(f[n+2]);
        }
    }
}

另注:卡特蘭數中f[2]=f[3]=1,f[4]=2,f[5]=5。。。,並不是從一開始的,做本題時要錯2位輸出。