HDU1134

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
  
  
2 3 -1
 

Sample Output
  
  
2 5
 

Source


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

卡特兰数的前几项为: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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值