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
看到這個題的第一反應是卡特蘭數,第二反應是數據的可能性要遠大於卡特蘭數。
其實問題的根源就出在了根節點上,只要固定住根節點。下面的二叉樹分佈方式就和圓括號又或是棧順序一樣的問題了。
固定住根節點,
剩下的 左 0則右為n-1….一直到左n-1右0
說白了就是h(n)=h(0)*h(n-1)+h(1)*h(n-2)+….h(n-1)*h(0);
自然這就是卡特蘭數的計算公式了,接下來只需要將公式乘以根節點的個數就可以了
最後公式就是
a[i] = a[i - 1] * (4 * (i - 1) + 2)*i;
剩下的問題就是大數運算,唯一需要變更的就是 把二維數組的列開得寬一點就好,不然會爆。
加油!
#include<iostream>
#include<cstring>
using namespace std;
#define maxn 120
long long int a[maxn][500];//儲存卡特蘭數
long long int b[maxn];//n對應卡特蘭數的長度
void Catalan()//卡特蘭數計算函數
{
//計算公式:h(n)=h(n-1)*(4*n-2)/(n+1);
//大數運算
long long int i, j, len, carry, temp;
a[1][0] = b[1] = 1;
a[0][0] = 0;
len = 1;
for (i = 2; i <= 100; i++)
{
for (j = 0; j < len; j++)//len 始終等於前一個卡特蘭數的位數
{
a[i][j] = a[i - 1][j] * (4 * (i - 1) + 2)*i;
}
carry = 0;
for (j = 0; j < len; j++)//進位操作
{
temp = a[i][j] + carry;
a[i][j] = temp % 10;
carry = temp / 10;
}
while (carry)
{
a[i][len++] = carry % 10;
carry /= 10;
}
carry = 0;
for (j = len - 1; j >= 0; j--)//除法
{
temp = carry * 10 + a[i][j];
a[i][j] = temp / (i + 1);
carry = temp % (i + 1);
}
while (!a[i][len - 1])
len--;
b[i] = len;
}
}
int main()
{
int n;
Catalan();//打表
while (~scanf("%d", &n)&&n)
{
for (int k = b[n] - 1; k >= 0; k--)
{
printf("%d", a[n][k]);
}
printf("\n");
}
return 0;
}