Game of Connections
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. Input Each line of the input file will be a single positive number n, except the last line, which is a number -1. 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个人围成一圈,两两互相连接,且连接的线不能交叉,问有多少种方式。 分析:根据数据可以推出是Catalan数,根据Calalan的递推式:h(n) = h(n-1)*(4n-2)/(n+1)可以计算,又因为数据比较大,所以需要模拟大数的乘法和除法。 更多求卡特兰数的模板(点这里) |
代码实现:
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
#define MAX 100
#define BASE 10000
void multiply(int a[],int Max,int b)
{//大数乘法
int i,array=0;
for(i=Max-1;i>=0;i--)
{
array += b*a[i];
a[i] = array%BASE;
array /= BASE;
}
}
void divide(int a[],int Max,int b)
{//大数除法
int i,div=0;
for(i=0;i<Max;i++)
{
div =div * BASE + a[i];
a[i] = div/b;
div%=b;
}
}
int main()
{
int i,j,n;
int a[105][MAX];
memset(a[1],0,sizeof(a[1]));
for(i=2,a[1][MAX-1]=1;i<=100;i++)
{
memcpy(a[i],a[i-1],sizeof(a[i-1]));
multiply(a[i],MAX,4*i-2);
divide(a[i],MAX,i+1);
}
while(cin>>n,n!=-1)
{
for(i=0;i<MAX && a[n][i]==0;i++);
cout<<a[n][i++];
for(;i<MAX;i++)
printf("%04d",a[n][i]);
cout<<endl;
}
return 0;
}