1. 程式人生 > >【HDU - 1134 】Game of Connections(JAVA大數加法,卡特蘭數)

【HDU - 1134 】Game of Connections(JAVA大數加法,卡特蘭數)

題幹:

This is a small but ancient game. You are supposed to write down the numbers 1, 2, 3, ... , 2n - 1, 2n consecutively in clockwise order on the ground to form a circle, and then, to draw some straight line segments to connect them into number pairs. Every number must be connected to exactly one another. And, no two segments are allowed to intersect. 

It's still a simple game, isn't it? But after you've written down the 2n numbers, can you tell me in how many different ways can you connect the numbers into pairs? Life is harder, right? 

Input

Each line of the input file will be a single positive number n, except the last line, which is a number -1. You may assume that 1 <= n <= 100. 

Output

For each n, print in a single line the number of ways to connect the 2n numbers into pairs. 

Sample Input

2
3
-1

Sample Output

2
5

解題報告:

  找規律題。。每次都從1號頂點開始找,發現是有遞推規律的、、然後longlong了好幾發還以為是思路不對,,一看輸入70的時候是個負數、、所以果斷轉Java大整數類、、比賽的時候有事出去了就沒提交,,回來一發AC2333、、Java大法好啊、、

  查題解後發現是卡特蘭數?這個不是處理棧的問題的嗎、、沒深入學習過、、

AC程式碼:

import java.math.BigInteger;
import java.util.Scanner;
public class Main {
    public static void  main(String[] args) {
        Scanner cin = new Scanner(System.in);
        BigInteger[] a = new BigInteger[205];
        a[1]=a[0]=BigInteger.valueOf(1);
        for(int i = 2; i<=200; i++) a[i]=BigInteger.valueOf(0);
        for(int i = 2; i<=102; i++) {
            for(int j = 0; j<i; j++) {
                BigInteger tmp = BigInteger.valueOf(0);
                tmp=a[j];
                tmp=tmp.multiply(a[i-j-1]);
                //System.out.println(a[i]);
                a[i]=a[i].add(tmp);

            }
        }
        while(cin.hasNext()) {
            int x = cin.nextInt();
            if(x == -1) break;
            System.out.println(a[x]);
        }

    }
}

總結:用Java大數的陣列的時候一定別忘了例項化物件陣列的時候要附上初值,不然指向NULL。。就沒法進行操作了、。