POJ 2084 Game of Connections ——————Catalan 数

版权声明:听说这里是写版权声明的 https://blog.csdn.net/Hpuer_Random/article/details/81870167

Game of Connections

Language:Default
Game of Connections
Time Limit: 1000MS Memory Limit: 30000K
Total Submissions: 9203 Accepted: 4512

Description

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

Source

—– C a t a l a n 数 (卡特兰数,又称卡塔兰数)是组合数学中一个常出现在各种计数问题中出现的数列。前几项为 1   ,   1   ,   2   ,   5   ,   14   ,   42   ,   132   h ( 1 ) = 1   ,   h ( 0 ) = 1   ,   C a t a l a n   数满足递归式:

h ( n ) = h ( 0 ) × h ( n 1 )   +   h ( 1 ) × h ( n 2 )   +     + h ( n 1 )   ×   h ( 0 ) ( n 2 )

也就是
h ( n ) = i = 0 n 1 h ( i ) h ( n i 1 )

另类递归式:

h ( n )   =   4 × n 2 n + 1 × h (   n 1 )

该递推关系的的解是:
h ( n ) = C   2 n   n n + 1 ( n = 1 , 2 , 3 )


由于Catalan数非常大,需要用大数来解决

#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
const int MAX=100;
const int BASE=10000;

void multiply(int a[],int Max,int b)//大数乘法
{
    int i,array=0;
    for(i=Max -1;i>=0;i--)
    {
        array += b*a[i];
        a[i] = array%BASE;
        array /= BASE;
    }
}

void divide(int a[],int Max,int b)//大树除法
{
    int i,div=0;
    for(i=0;i<Max;i++)
    {
        div=div*BASE + a[i];
        a[i] = div / b;
        div %= b;
    }
}
int main()
{
    int a[101][MAX],i,j,n;
    memset(a[1],0,MAX*sizeof(int));
    for(i=2,a[1][MAX-1]=1;i<101;i++)
    {
        memcpy(a[i],a[i-1],MAX*sizeof(int));    //h[i] = h[i-1]
        multiply(a[i],MAX,4*i-2);               //h[i] *= (4*i-2)
        divide(a[i],MAX,i+1);                   //h[i] /= (i+1)
    }
    while(cin>>n)
    {
        if(n==-1)   break;
        for(i=0;i<MAX && a[n][i]==0 ; i++) ;
        cout<<a[n][i++];
        for(;i<MAX;i++)
            printf("%04d",a[n][i]);
        cout<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Hpuer_Random/article/details/81870167
今日推荐