HDU1023 Train Problem II【卡特兰数+大数+亿进制+打表】

Train Problem II

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


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.

问题链接:HDU1023 Train Problem II

问题简述:(略)

问题分析

  这个问题是卡特兰数计算问题,第100项是一个大数。同时,打表是一个好的主意。

  卡特兰数是OEIS中序号为A000108的数列。

  卡特兰数计算公式是:C_0 = 1 /quad , /quad C_{n+1}=/frac{2(2n+1)}{n+2}C_n

程序说明

  程序中使用亿进制进行计算,数组catalan[n](第n行)表示第n个卡特兰数,catalan[n][0]存放位数,下标从小到大是从低位到高位,每一位的权是1亿(100000000)。

  参考链接中有有关万进制的说明,亿进制的原理与万进制是相似的,就不做详细解释了,参见参考链接。

  对于64位计算机而言,亿进制应该要比万进制算得更快。

题记:(略)


参考链接:HDU1042 n!【大数+万进制】


AC的C语言程序如下:

/* HDU1023 Train Problem II */

#include 
#include 

typedef unsigned long long ULL;

#define HM 100000000

#define N 100
#define N2 10

ULL catalan[N+1][N2];

void setCatalan(int n)
{
    int i, j;

    memset(catalan, 0, sizeof(catalan));

    catalan[0][0] = 1;
    catalan[0][1] = 1;
    for(i=1; i<=n; i++) {
        /* 各个亿进制位做乘法 */
        for(j=1; j <= (int)catalan[i - 1][0]; j++)
            catalan[i][j] = 2 * (2 * (i - 1) + 1) * catalan[i - 1][j];

        ULL r1 = 0, r2;
        /* 各个亿进制位做除法 */
        for(j=(int)catalan[i - 1][0]; j >= 1 ; j--) {
            r2 = (r1 * HM +catalan[i][j]) % (i + 1);
            catalan[i][j] = (r1 * HM +catalan[i][j]) / (i + 1);
            r1 = r2;
        }

        /* 进行亿进制调整 */
        for(j=1; j <= (int)catalan[i - 1][0]; j++) {
            catalan[i][j + 1] += catalan[i][j] / HM;
            catalan[i][j] %= HM;
        }

        catalan[i][0] = catalan[i][j] > 0 ? catalan[i - 1][0] + 1 : catalan[i - 1][0];
    }
}

int main(void)
{
    setCatalan(N);

    int n, i;

    while(~scanf("%d", &n)) {
        printf("%lld", catalan[n][catalan[n][0]]);
        for(i=(int)catalan[n][0]-1; i>=1; i--) {
            printf("%08lld", catalan[n][i]);
        }
        printf("\n");
    }

    return 0;
}






你可能感兴趣的:(#,ICPC-备用二,#,ICPC-大数,#,ICPC-HDU)