HDU1134-Game of Connections

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

分析:

题意:一个圈,然后在圈上顺时针表2n个点,该点的id按标点的顺序从1开始,画nt条线将点两两连接在一起,同时,要求任意的连线不能有交点,问有多少种方法?

解析:
卡塔兰数!

代码:

#include<iostream>
#include<cstdio>
#define N 105

using namespace std;

int dp[N][N];

int main()
{
	int n;
	dp[0][0]=dp[1][0]=dp[1][1]=1;
	dp[0][1]=0;
	for(int i=2;i<=100;i++)
	{
		int len=dp[i-1][0],v=0;
		int k=4*i-2;
		for(int j=1;j<=len;j++)
		{
			dp[i][j]=dp[i-1][j]*k+v;
			v=dp[i][j]/10;
			dp[i][j]%=10;
		}
		while(v)
		{
			dp[i][++len]=v%10;
			v/=10;
		}
		for(int j=len;j>0;j--)
		{
			v=v*10+dp[i][j];
			dp[i][j]=v/(i+1);
			v%=(i+1);
		}
		while(!dp[i][len])
		{
			len--;
		}
		dp[i][0]=len;
	}
	while(~scanf("%d",&n)&&n>-1)
	{
		for(int i=dp[n][0];i>0;i--)
		{
			printf("%d",dp[n][i]);
		}
		printf("\n");
	}
	return 0;
 }
发布了46 篇原创文章 · 获赞 16 · 访问量 379

猜你喜欢

转载自blog.csdn.net/weixin_43357583/article/details/105233926
今日推荐