Game of Connections HDU - 1134 (大数乘 + 记忆dp)

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

在一个环上,连接两个点可以把点分成两部分,其实每部分都是一个相同的子问题。因而就实现了递归,又因为子问题重复较多,所以可以记忆着递归。当然还要加上大数乘。

#include <iostream>
#include <cstring>
using namespace std;

int ans[150][500];

void add(int a[],int b[],int c[])
{
    int s = 0;
    for(int i = 0;i < 100; i++) // 因为100位已经比较大啦,这样就不用考虑溢出啦。。
    {
        int s_ = s; // 目的是想实现a = a+b
        s = (a[i]+b[i]+s)/10;
        c[i] = (a[i]+b[i]+s_)%10;

    }
}

void muti(int a[],int b[],int an[])
{

    memset(an,0,sizeof(an));
    int s = 0;
    for(int i = 0; i < 100; i++)
    {
        int tmp[300];
        memset(tmp,0,sizeof(tmp));
        for(int j = 0; j < 100; j++)
        {
            tmp[i+j] = a[i]*b[j];//这里不用考虑进位,因为我们是要算到100位的,加的时候就会进位啦。
        }
        add(tmp,an,an);
    }
}

int dp[250][155];

void get(int n) // 递归记忆
{

    if(n == 2 || n == 0)
    {
        return;
    }
    int sum[155];
    memset(sum,0,sizeof(sum));
    for(int i = 2; i <= n; i++)
    {
        if(i % 2 == 0)
        {
            if(!dp[n-i][151])  // 151 处用来标记是否已经处理过。
            {
              get(n-i);
              dp[n-i][151] = 1;
            }
            if(!dp[i-2][151])
            {
                get(i-2);
                dp[i-2][151] = 1;
            }
            int tmp[155];
            memset(tmp,0,sizeof(tmp));
            muti(dp[n-i],dp[i-2],tmp);
            add(tmp,sum,sum);
        }
    }
    for(int i = 0; i < 150; i++)
        dp[n][i] = sum[i];
}
int main()
{
    dp[2][0] = 1;
    dp[0][0] = 1;
    get(200);
    int n;
    while(cin >> n&&n!=-1)
    {
        int i;
        for(i = 150; i >= 1; i--)
        {
            if(dp[2*n][i] != 0) break;
        }
        while(i >= 0)
        {
            cout << dp[2*n][i--] ;
        }
        cout <<endl;
    }
    return 0;
}


  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值