您的位置:首页 > 其它

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

2017-11-10 18:19 323 查看
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? 

InputEach 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. 

OutputFor 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
[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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: