您的位置:首页 > 其它

杭电_ACM_How Many Trees

2012-11-05 23:26 363 查看
[align=left]Problem Description[/align]
A binary search tree is a binary tree with root k such that any node v reachable from its left has label (v) <label (k) and any node w reachable from its right has label (w) > label (k). It is a search structure which can find a node with label x in O(n log n) average time, where n is the size of the tree (number of vertices).

Given a number n, can you tell how many different binary search trees may be constructed with a set of numbers of size n such that each element of the set will be associated to the label of exactly one node in a binary search tree?

[align=left]Input[/align]
The input will contain a number 1 <= i <= 100 per line representing the number of elements of the set.

[align=left]Output[/align]
You have to print a line in the output for each entry with the answer to the previous question.

[align=left]Sample Input[/align]

1
2
3


[align=left]Sample Output[/align]

1
2
5


View Code

#include <stdio.h>
int a[101][200] = {0};
void catalan()
{
int carry, i, j, length, remainder;
a[1][1] = 1;
a[2][1] = 2;
a[3][1] = 5;
a[3][0] = 1;
for (i = 4; i <= 100; i++)
{
length = a[i - 1][0];
carry = 0;
//handle multipling
for (j = 1; j <= length; j++)
{
carry += a[i - 1][j] * (4 * i - 2);
a[i][j] = carry % 10;
carry /= 10;
}
//determine the length
while (carry)
{
a[i][length++] = carry % 10;
carry /= 10;
}
remainder = 0;
//handle dividing
for (j = length; j >= 1; j--)
{
remainder = remainder * 10 + a[i][j];
a[i][j] = remainder / (i + 1);
remainder %= (i + 1);
}
//determine the length
while (!a[i][length])
{
length--;
}
a[i][0] = length;
}
}
int main()
{
int num, i;
catalan();
while (scanf("%d", &num) != EOF)
{
if (num < 4)
printf("%d\n", a[num][1]);
else
{
for (i = a[num][0]; i >= 1; i--)
{
printf("%d", a[num][i]);
}
puts("");
}
}
return 0;
}


Key points

firstly, you must realize that it's a calatan question. Then you can solve it.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: