hdu Game of Connections

Game of Connections

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 401    Accepted Submission(s): 265
 
Problem 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
Asia 2004, Shanghai (Mainland China), Preliminary
 
Recommend
Eddy
 

分析:大数运算以及卡特兰数的应用,即递推式的应用。

令h(0)=1,h(1)=1,catalan数满足递推式[1]

 

  h(n)= h(0)*h(n-1)+h(1)*h(n-2) + ... + h(n-1)h(0) (n>=2)

 

  例如:h(2)=h(0)*h(1)+h(1)*h(0)=1*1+1*1=2

 

  h(3)=h(0)*h(2)+h(1)*h(1)+h(2)*h(0)=1*2+1*1+2*1=5

 

  另类递推式[2]

 

  h(n)=h(n-1)*(4*n-2)/(n+1);

 

  递推关系的解为:

 

  h(n)=C(2n,n)/(n+1) (n=1,2,3,...)

 

  递推关系的另类解为:

 

  h(n)=c(2n,n)-c(2n,n+1)(n=1,2,3,...)

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<string>
using namespace std;
#define MAX 100
#define BASE 10000
int fac[210][MAX];
void mult(int a[],int b)
{
    int i,temp=0;
    for(i=MAX-1;i>=0;--i)
    {
        temp=b*a[i]+temp;
        a[i]=temp%BASE;
        temp=temp/BASE;
    }
}
void div(int a[],int b)
{
    int i,temp=0;
    for(i=0;i<MAX;++i)
    {
        temp=temp*BASE+a[i];
        a[i]=temp/b;
        temp=temp%b;
    }
}
void make()
{
    int i;
    fac[0][MAX-1]=1;
    for(i=1;i<=100;++i)
    {
        memcpy(fac[i],fac[i-1],MAX*sizeof(int));
        mult(fac[i],(4*i-2));
        div(fac[i],i+1);
    }
}
void print(int a[])
{
    int i;
    for(i=0;i<MAX;++i)
    {
        if(a[i])
            break;
    }
    printf("%d",a[i++]);
    for(;i<MAX;++i)
    {
        printf("%04d",a[i]);
    }
    printf("\n");
}
int main()
{
    int m;
    make();
    while(scanf("%d",&m)!=EOF && m!=-1)
    {
        print(fac[m]);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/baidongtan/p/2664594.html