卡特兰数真是一个神奇的数字,很多组合问题的数量都和它有关系,例如:
XXXYYY XYXXYY XYXYXY XXYYXY XXYXYY
((())) ()(()) ()()() (())() (()())
((ab)c)d (a(bc))d (ab)(cd) a((bc)d) a(b(cd))
引用:http://blog.163.com/kevinlee_2010/blog/static/169820820201010894212352/
求一个数的卡塔兰数
使用递推式 H(n) = c(2n,n)/n+1;
改写为A(2n,n)/ (n+1)!
使用大数相乘相除计算
#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;
#define N 250
int a[N];
void init(int n)
{
memset(a,0,sizeof(a));
a[0] = 1;
int i = 0;
int j = 0;
int k1 = 1;
for(i = 2*n; k1 <= n; i--,k1++)
{
int t = 0;
int mul = 0;
for(j = 0; j <= N; j++)
{
mul = a[j] *i + t;
a[j] = mul % 10;
t = mul / 10;
}
}
for(i = 2; i <= n+1; i++)
{
int t1 = 0;
int mul1 = 0;
for(j = N; j >= 0;j--)
{
mul1 = mul1 *10 + a[j];
a[j] = mul1 / i;
mul1 %= i;
}
}
int k = N;
while(k--)
if(a[k])
break;
k += 1;
while(k--)
printf("%d",a[k]);
printf("\n");
}
int main()
{
int n;
while(scanf("%d",&n) != EOF)
{
if(n < 2)
printf("%d\n",1);
else
init(n);
}
return 0;
}