Problem Description
As we all know the Train Problem I, the boss of the Ignatius Train Station want to know if all the trains come in strict-increasing order, how many orders that all the trains can get out of the railway.
Input
The input contains several test cases. Each test cases consists of a number N(1<=N<=100). The input is terminated by the end of file.
Output
For each test case, you should output how many ways that all the trains can get out of the railway.
Sample Input
1 2 3 10
Sample Output
1 2 5 16796HintThe result will be very large, so you may not process it by 32-bit integers.
Author
Ignatius.L
答案:
注:
卡特兰数:卡特兰数又称卡塔兰数,是组合数学中一个常出现在各种计数问题中出现的数列。由以比利时的数学家欧仁·查理·卡塔兰 (1814–1894)命名。
原理:
令h(1)=1,h(0)=1,catalan数满足递归式: h(n)= h(0)*h(n-1)+h(1)*h(n-2) + ... + h(n-1)h(0) (其中n>=2) 另类递归式: h(n)=((4*n-2)/(n+1))*h(n-1); 该递推关系的解为: h(n)=C(2n,n)/(n+1) (n=1,2,3,...)
卡特兰数的应用:实质上都是递归等式的应用
#include <stdio.h>
#include <string>
#include <cmath>
char string[10000];
char out[10000];
char out[10000];
void calculate(long n)
{
if (n == 1)
{
string[0] = '1';
out[0] = '1';
}
else
{
long v = (4*n-2);
long d = (n+1);
long space = 0;
long w, i, s, le, k;
{
if (n == 1)
{
string[0] = '1';
out[0] = '1';
}
else
{
long v = (4*n-2);
long d = (n+1);
long space = 0;
long w, i, s, le, k;
if (d < 10)
space = 1;
else if (d < 100)
space = 2;
else
space = 3;
space = 1;
else if (d < 100)
space = 2;
else
space = 3;
calculate(n-1);
// multiplication
le = strlen(string);
s = 0;
for (i = 0; i < le; ++i)
{
w = v*(string[i]-'0')+s;
string[i] = w%10 + '0';
s = w/10;
}
while (s > 0)
{
string[i++] = s%10 + '0';
s = s/10;
}
// division
memset(out, 0, sizeof(out));
le = strlen(string);
s = 0;
w = 0;
k = 0;
for (i = 0; i < space; ++i)
w += pow(10, space-i-1)*(string[le-i-1]-'0');
for (i = space; i < le; ++i)
{
if (k != 0 || w/d != 0)
out[k++] = w/d + '0';
s = w%d;
w = string[le-i-1]-'0'+10*s;
}
out[k++] = w/d + '0';
// multiplication
le = strlen(string);
s = 0;
for (i = 0; i < le; ++i)
{
w = v*(string[i]-'0')+s;
string[i] = w%10 + '0';
s = w/10;
}
while (s > 0)
{
string[i++] = s%10 + '0';
s = s/10;
}
// division
memset(out, 0, sizeof(out));
le = strlen(string);
s = 0;
w = 0;
k = 0;
for (i = 0; i < space; ++i)
w += pow(10, space-i-1)*(string[le-i-1]-'0');
for (i = space; i < le; ++i)
{
if (k != 0 || w/d != 0)
out[k++] = w/d + '0';
s = w%d;
w = string[le-i-1]-'0'+10*s;
}
out[k++] = w/d + '0';
// exchange
memset(string, 0, sizeof(string));
for (k = strlen(out)-1, i = 0; k >= 0; --k)
{
string[i++] = out[k];
}
}
}
memset(string, 0, sizeof(string));
for (k = strlen(out)-1, i = 0; k >= 0; --k)
{
string[i++] = out[k];
}
}
}
int main(int argc, char* argv[])
{
long n;
{
long n;
while (scanf("%d", &n)!=EOF && n)
{
memset(string, 0, sizeof(string));
calculate(n);
printf("%s/n", out);
}
return 0;
}
{
memset(string, 0, sizeof(string));
calculate(n);
printf("%s/n", out);
}
return 0;
}