HDU1134

来源:互联网 发布:c语言项目开发流程 编辑:程序博客网 时间:2024/06/11 21:42

Game of Connections

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



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
23-1
 

Sample Output
25
 

Source
Asia 2004, Shanghai (Mainland China), Preliminary


此题考查的是卡特兰数,由于卡特兰数很大,所以考虑大数处理。

卡特兰数的前几项为:h(0)=1;h(1)=1;h(2)=2;h(3)=5……

卡特兰数的递推公式为:h(n)=h(n-1)*(4*n-2)/(n+1);

非递推公式为C(2n,n)/(n+1);

此题用递推公式求解,并用到大数的乘法和大数的乘法处理,本题对卡特兰数的前100项做了预处理:



#include <iostream>#include <cstdio>#include <cstring>using namespace std;const int maxn = 110;const int mod = 10000;//4位存入int c[maxn][maxn]={0};//大整数乘法//注意进位是不用*n的void multiply(int a[],int n){    int vis = 0;//进位    for(int i = 0;i < maxn;i++)    {        vis += a[i] * n;        a[i] = vis % mod;        vis /= mod;    }}//大整数除法void divide(int a[],int n){    int vis = 0;//向上请求    for(int i = maxn-1;i >= 0 ;i--)    {        vis = vis * mod + a[i];        a[i] = vis / n;        vis %= n;    }}int main(){    c[0][0] = 1;    c[1][0] = 1;    for(int i = 2;i < maxn;i++)    {        memcpy(c[i],c[i-1],maxn*sizeof(int));        multiply(c[i],4*i-2);        divide(c[i],i+1);    }    int n;    while(scanf("%d",&n)&&n != -1)    {        int i;        for(i = maxn-1;i >= 0;i--)            if(c[n][i] != 0) break;        printf("%d",c[n][i]);        for(i = i - 1;i >= 0;i--)            printf("%04d",c[n][i]);        printf("\n");    }    return 0;}




0 0
原创粉丝点击