您的位置:首页 > 大数据 > 人工智能

hdoj1023 Train Problem II

2016-01-19 11:43 711 查看

Train Problem II

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)

Total Submission(s): 7333    Accepted Submission(s): 3946


[align=left]Problem Description[/align]
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.

 

[align=left]Input[/align]
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.

 

[align=left]Output[/align]
For each test case, you should output how many ways that all the trains can get out of the railway.

 

[align=left]Sample Input[/align]

1
2
3
10

 

[align=left]Sample Output[/align]

1
2
5
16796

Hint
The result will be very large, so you may not process it by 32-bit integers.

 
解题思路:由测试用例可看出是这是卡特兰数

卡特兰数又称卡塔兰数,英文名Catalan number,是组合数学中一个常出现在各种计数问题中出现的数列。以比利时的数学家欧仁·查理·卡塔兰 (1814–1894)的名字来命名,其前几项为 : 1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786, 208012, 742900, 2674440, 9694845, 35357670, 129644790, 477638700, 1767263190,
6564120420, 24466267020, 91482563640, 343059613650, 1289904147324, 4861946401452, ...

令h(0)=1,h(1)=1,catalan数满足递推式

h(n)= h(0)*h(n-1)+h(1)*h(n-2) + ... + h(n-1)h(0) (n>=2)

另类递推式

h(n)=h(n-1)*(4*n-2)/(n+1);

我是用的这个递推式做的

首先将h(n-1)和(4*n-2)看做大数乘法,所得值保留到h(n-1)中,然后将h(n-1)和(n+1)看做大数除法。最后即为得数。

#include <stdio.h>
#include <string.h>
int a[10000],count;
void bigMul(int y)//大数除法
{    int i,car = 0;
for(i=0;i<=count;i++)
{    a[i] = a[i] * y + car;
car = a[i] / 10;
a[i] %= 10;
}
if(car > 0)
{
a[++count] = car;
}
}
void bigDiv(int y)//大数乘法
{
int i,temp,ret = 0;
for(i=count;i>=0;i--)
{
temp = a[i] + ret;
a[i] = temp / y;
ret = temp % y * 10;
}
}
int main()
{
int n,i,j;
while(scanf("%d",&n)!=EOF){
if(n == 0 || n == 1)
{
printf("1\n");
continue;
}
memset(a,0,sizeof(a));
a[0] = 1;
count = 0;
for(i=2;i<=n;i++) {
bigMul((4*i-2));
bigDiv((i+1));
}
if(a[count] != 0)//处理第一个为零的情况
{
printf("%d",a[count]);
}
for(i=count-1;i>=0;i--)
{
if(!a[i])//数的前面为0不输出
continue;
while(i>=0)
printf("%d",a[i--]);
}
printf("\n");
}
return 0;}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: