Train Problem IITime Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 2375 Accepted Submission(s): 1359
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 1679 |
这是一个catalan数,还要用到大数,开始的时候就没有用到,晕。。。
Catalan数
中文:卡特兰数
原理:
令h(1)=1,catalan数满足递归式:
h(n)= h(1)*h(n-1) + h(2)*h(n-2) + ... + h(n-1)h(1) (其中n>=2)
另类递归式:
h(n)=((4*n-6)/(n))*h(n-1);
该递推关系的解为:
h(n)=C(2n-2,n-1)/(n) (n=1,2,3,...)
我并不关心其解是怎么求出来的,我只想知道怎么用catalan数分析问题。
我总结了一下,最典型的四类应用:(实质上却都一样,无非是递归等式的应用,就看你能不能分解问题写出递归式了)
1.括号化问题。
矩阵链乘: P=a1×a2×a3×……×an,依据乘法结合律,不改变其顺序,只用括号表示成对的乘积,试问有几种括号化的方案?(h(n-1)种)
2.出栈次序问题
一个栈(无穷大)的进栈序列为1,2,3,..n,有多少个不同的出栈序列?(h(n+1)种?)
类似:有2n个人排成一行进入剧场。入场费5元。其中只有n个人有一张5元钞票,另外n人只有10元钞票,剧院无其它钞票,问有多少中方法使得只要有10元的人买票,售票处就有5元的钞票找零?(将持5元者到达视作将5元入栈,持10元者到达视作使栈中某5元出栈)
3.将多边行划分为三角形问题。
将一个凸多边形区域分成三角形区域的方法数?
类似:一位大城市的律师在她住所以北n个街区和以东n个街区处工作。每天她走2n个街区去上班。如果她
从不穿越(但可以碰到)从家到办公室的对角线,那么有多少条可能的道路?
类似:在圆上选择2n个点,将这些点成对连接起来使得所得到的n条线段不相交的方法数?
4.给顶节点组成二叉树的问题。
给定N个节点,能构成多少种形状不同的二叉树?
(一定是二叉树!
先去一个点作为顶点,然后左边依次可以取0至N-1个相对应的,右边是N-1到0个,两两配对相乘,就是h(0)*h(n-1) + h(2)*h(n-2) + ... + h(n-1)h(0)=h(n))
(能构成h(N)个)
【wolf5x】请教:能解释一下二叉树和二叉排序树的定义的区别吗?如图所示:二叉树已经画了九种不同的,而f(3)=5!
(是指形状相同的2叉数,准确说你的里面好多重复的,第2,3个就是重复的,因为形状相同.2叉树不应该把节点编号的,因为每个节点都是相同的东西!)
/*
Name:
Copyright:
Author:
Date: 22/10/11 11:55
Description:
*/
#include <cstdlib>
#include <iostream>
using namespace std;
int ans[100];
void mutil(int x)
{
int yushu=0;
for(int i=0;i<100;i++)
{
yushu+=ans[i]*x;
ans[i]=yushu%10000;
yushu/=10000;
}
}
void div(int x)
{
int t=0;
for(int i=99;i>=0;i--)
{
t+=ans[i];
ans[i]=t/x;
t=t%x*10000;
}
}
int main(int argc, char *argv[])
{
int n;
while(scanf("%d",&n)!=EOF)
{
// __int64 ans=1;
//cout<<n<<" d";
//for(int i=0;i<100;i++) ans[i]=0;
memset(ans,0,sizeof(ans));
ans[0]=1;
for(int i=1;i<=n;i++)
{
mutil(n+i);
div(i);
}
// for(int i=0;i<100;i++)
// cout<<ans[i];
div(n+1);
// ans=ans*(n+i)/i;
// ans/=(n+1);
int j=99;
while(ans[j]==0) j--;
printf("%d",ans[j]); j--;
for(int i=j;i>=0;i--)
printf("%04d",ans[i]);
putchar(10);
}
system("PAUSE");
return EXIT_SUCCESS;
}