您的位置:首页 > 其它

杭电OJ——1131 Count the Trees(卡特兰数的应用)

2013-01-16 12:54 375 查看


Count the Trees

Problem Description

Another common social inability is known as ACM (Abnormally Compulsive Meditation). This psychological disorder is somewhat common among programmers. It can be described as the temporary (although frequent) loss of the faculty of speech when the whole power
of the brain is applied to something extremely interesting or challenging.

Juan is a very gifted programmer, and has a severe case of ACM (he even participated in an ACM world championship a few months ago). Lately, his loved ones are worried about him, because he has found a new exciting problem to exercise his intellectual powers,
and he has been speechless for several weeks now. The problem is the determination of the number of different labeled binary trees that can be built using exactly n different elements.

For example, given one element A, just one binary tree can be formed (using A as the root of the tree). With two elements, A and B, four different binary trees can be created, as shown in the figure.



If you are able to provide a solution for this problem, Juan will be able to talk again, and his friends and family will be forever grateful.



Input

The input will consist of several input cases, one per line. Each input case will be specified by the number n ( 1 ≤ n ≤ 100 ) of different elements that must be used to form the trees. A number 0 will mark the end of input and is not to be processed.



Output

For each input case print the number of binary trees that can be built using the n elements, followed by a newline character.



Sample Input

1
2
10
25
0




Sample Output

1
4
60949324800
75414671852339208296275849248768000000




Source

UVA



Recommend

Eddy
这道题目是关于卡特兰数应用的问题!关于卡特兰数,看看这篇博文吧!http://blog.csdn.net/lishuhuakai/article/details/8034075
下面发代码吧!
//典型的卡特兰数的应用
//判定二叉树的数量!假设有n个节点,一共有h(n)种数
//可以这样考虑:先选定一个节点为根节点,则还余下n-1个节点
//如果根节点左子树无节点,则右子树有n-1个节点
//如果左子树有1个节点,则右子树有n-2个节点~~~
//因此一共的种数是h(n)=h(0)*h(n-1)+h(1)*h(n-1)+~~~+h(n-1)*h(0)
//而这恰好是卡特兰数的表达式!卡特兰数一般的表达式为h(n)=(2*n)!/[(n+1)!*n!]  (n>=2)

#include<iostream>
using namespace std;
#define MAX 101
#define BASE 10000

void multiply(int a[],int len,int b)
{
	for(int i=len-1,carry=0;i>=0;--i)
	{
		carry=carry+b*a[i];
		a[i]=carry%BASE;
		carry=carry/BASE;
	}
}

void divide(int a[],int len,int b)
{
	for(int i=0,div=0;i<len;i++)
	{
		div=div*BASE+a[i];
		a[i]=div/b;
		div=div%b;
	}
}

int main()
{
	int i,j,h[101][MAX];
	int a[MAX];
	memset(h[1],0,MAX*sizeof(int));
	for(i=2,h[1][MAX-1]=1;i<=100;i++)
	{
		memcpy(h[i],h[i-1],MAX*sizeof(int));
		multiply(h[i],MAX,4*i-2);
		divide(h[i],MAX,i+1);
	}

	while(cin>>i && i>=1 && i<=100)
	{
		memcpy(a,h[i],MAX*sizeof(int));
		for(j=2;j<=i;j++)
	    multiply(a,MAX,j);
		
		for(j=0;j<MAX && a[j]==0;j++);
        printf("%d",a[j++]);
		for(;j<MAX;j++)
		printf("%04d",a[j]);
		   printf("\n");

	}

	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: