Count the Trees
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 1572 Accepted Submission(s): 1044
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.
本題爲經典的卡特蘭數問題。在不考慮順序(即字母順序),將結點編號爲0~n-1;任取一個節點k作根節點,從而衍生出兩個子問題f(k-1)和f(n-k),有f(k-1)*f(n-k)棵樹;則
f(n)=f(0)(n-1)+f(1)f(n-1)+.......+f(n-1)*f(0);符合卡特蘭數的遞推公式。詳見點擊打開鏈接。有該遞推公式可以推出f(n)=f(n-1)*(4n-2)/(n+1);好!現在卡特蘭數的問題解決了,來看
加入字母順序以後,這可以看成已經準備好了n個位置,現在要按排座位,這是個排序問題,排序總數爲n!種!所以數的數量就等於:f(n)*n!;別!別以爲現在就解決問題了。來看看題目吧!n可以達到100。f(100)的位數可以達到60~80!具體自己去數吧!而100!的位數可以達到160左右。任何數值類型都不能容納!所以又是個高精度問題。本想
先算出1-100的卡特蘭數,在算出1-100的階乘,再相乘!但很不理想!兩個都是大數。很複雜!還沒涉及!所以改成h(n)=h(n-1)*n*(4n-2)/(n+1)(h(n)爲數的數量).這裏乘法和除法要分開進行。
來看看我的代碼吧!
#include <stdio.h>
#include <iostream>
#include <string.h>
#include <queue>
#include <algorithm>
#include <math.h>
#define MIN(a,b) (a) < (b) ? (a) : (b)
#define M 250 //結果的最長位數
using namespace std;
int num[100][M]; //存放1~100的樹的數量
int temp[M];
void init()
{
int i,j,c,temp;
num[1][0]=1;
for(i=2;i<=100;i++)//枚舉1-100
{
for(j=0,c=0;j<M;j++) //乘於i*(4*i-2);
{
num[i][j]=num[i-1][j]*i*(4*i-2)+c;
c=num[i][j]/10;
num[i][j]%=10;
}
for(j=M-1,c=0;j>=0;j--) //除於(i+1);
{
temp=num[i][j]+c*10;
num[i][j]=temp/(i+1);
c=temp%(i+1);
}
}
}
//輸出結果
void print(int n)
{
int i,flag=0;//flag用於標記發現數字的最高位,如果沒有發現,則數爲0
for(i=M-1;i>=0;i--)
{
if(num[n][i]||flag) //發現以後無論0還是非零都輸出
{
printf("%d",num[n][i]);
flag=1;
}
}
if(!flag)
printf("0");
printf("\n");
}
int main()
{
int n,T;
init();
while(scanf("%d",&n)&&n>0)
{
memset(temp,0,sizeof(temp));//對temp初始化爲0
print(n);
}
return 0;
}