poj2084 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. 
And, no two segments are allowed to intersect. 

It's still a simple game, isn't it? But after you've written down the 2n numbers, can you tell me in how many different ways can you connect the numbers into pairs? Life is harder, right?


Input
Each line of the input file will be a single positive number n, except the last line, which is a number -1. 

You may assume that 1 <= n <= 100.


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


卡特兰数的典型应用为如下这些问题:

1.括号化问题:矩阵链乘: P=a1×a2×a3×……×an,依据乘法结合律,不改变其顺序,只用括号表示成对的乘积,试问有几种括号化的方案?(h(n))

2.出栈次序问题:一个栈(无穷大)的进栈序列为123,…,n,有多少个不同的出栈序列?

与出栈问题类似的一个题目:2n个人排成一行进入剧场。入场费5元。其中只有n个人有一张5元钞票,另外n人只有10元钞票,剧院无其它钞票,问有多少中方法使得只要有10元的人买票,售票处就有5元的钞票找零?(将持5元者到达视作将5元入栈,持10元者到达视作使栈中某5元出栈)

3.凸多边形的三角剖分问题:求将一个凸多边形区域分成三角形区域的方法数。

类似的题目(1):一位大城市的律师在她住所以北n个街区和以东n个街区处工作。每天她走2n个街区去上班。如果她从不穿越(但可以碰到)从家到办公室的对角线,那么有多少条可能的道路?

类似的题目(2):在圆上选择2n个点,将这些点成对连接起来使得所得到的n条线段不相交的方法数?

4.用给定节点组成二叉树的问题:给定N个节点,能构成多少种不同的二叉树?(能构成hN)个)

 

这道题只需稍微琢磨一下,就可以发现它的实质还是凸多边形的三角剖分问题。

代码:

#include
using namespace std;
int cal[109][109]; ///卡特兰数cal[i][j];i代表第i个卡特兰数,j代表当前卡特兰数的第j位
int len[109]; ///用于存储各个卡特兰数的长度

void getCal()
{
    len[1] = 1;
    cal[1][0] = 1;

    int carry;  ///用于控制进位
    int temp;
    int tempLen = 1;
    for(int i=2;i<=100;i++)
    {
        for(int j=0;j=0;j--)  ///处理除法,与手算除法的道理一样:从高位往低位算
        {
            temp = carry*10 + cal[i][j];
            cal[i][j] = temp/(i+1);
            carry = temp%(i+1);
        }

        while(cal[i][tempLen-1]==0)  ///如果最高位是0的话,则不算数
        {
            tempLen --;
        }

        len[i] = tempLen;
    }
}
int main()
{
    getCal();
    int n;
    while(cin>>n)
    {
        if(-1==n)
        {
            break;
        }
        for(int i=len[n]-1;i>=0;i--)
        {
            cout<



你可能感兴趣的:(ACM算法——卡特兰数)