Train Problem II

问题陈述:

  HDOJ Problem - 1023

 

问题解析:

  卡特兰数(Catalan)的应用

  基本性质:

  f(n) = f(1)f(n-1) + f(2)f(n-2) + ... + f(n-2)f(2) + f(n-1)f(1); 

  f(n) = C(2n, n) / (n+1) = C(2n-2, n-1) / n;

    C= (4n-2)/(n+1) Cn-1

 

代码详解:

I: C++  

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <memory.h>
 4 
 5 using namespace std;
 6 
 7 #define MAX 101
 8 #define BASE 10000
 9 
10 void multiply(int a[], int len, int b) {
11     for(int i=len-1, carry=0; i>=0; i--) {
12         carry += b * a[i];
13         a[i] = carry % BASE;
14         carry /= BASE;
15     }
16 }
17 
18 void divide(int a[], int len, int b) {
19     for(int i=0, div=0; i<len; i++) {
20         div = div * BASE + a[i];
21         a[i] = div / b;
22         div %= b;
23     }
24 }
25 
26 int main()
27 {
28     int i, j, h[101][MAX];
29     memset(h[1], 0, MAX*sizeof(int));
30     for(i=2, h[1][MAX-1]=1; i<=100; i++) {
31         memcpy(h[i], h[i-1], MAX*sizeof(int));
32         multiply(h[i], MAX, 4*i-2);
33         divide(h[i], MAX, i+1);
34     }
35 
36     while(cin >> i && i>=1 && i <= 100) {
37         for(j=0; j<MAX && h[i][j]==0; j++);
38         printf("%d", h[i][j++]);
39         for(; j<MAX; j++)
40             printf("%04d", h[i][j]);
41         cout << endl;
42     }
43     return 0;
44 }

 II: Java

 1 import java.io.BufferedInputStream;
 2 import java.math.BigInteger;
 3 import java.util.Scanner;
 4 
 5 public class Main {
 6     
 7     public static void main(String[] args) {
 8         Scanner sc = new Scanner(new BufferedInputStream(System.in));
 9         int n;
10         while(sc.hasNext()) {
11             BigInteger catalan = BigInteger.valueOf(1);
12             n = sc.nextInt();
13             for(int i=1; i<=n; i++) {
14                 catalan = catalan.multiply(BigInteger.valueOf(4*i-2)).divide(BigInteger.valueOf(i+1));
15             }
16             System.out.println(catalan);
17         }
18         sc.close();
19     }
20 }

 

参考资料:

  维基百科

  CSDN

 

转载请注明出处:http://www.cnblogs.com/michaelwong/p/4346692.html

posted @ 2015-03-18 11:30  HelloMichaelWong  阅读(462)  评论(0编辑  收藏  举报