杭电_ACM_How Many Trees

Problem Description
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? 
 
Input
The input will contain a number 1 <= i <= 100 per line representing the number of elements of the set.
 
Output
You have to print a line in the output for each entry with the answer to the previous question.
 
Sample Input
1
2
3
 
Sample Output
1
2
5
View Code
 1 #include <stdio.h>
 2 int a[101][200] = {0};
 3 void catalan()
 4 {
 5     int carry, i, j, length, remainder;
 6     a[1][1] = 1;
 7     a[2][1] = 2;
 8     a[3][1] = 5;
 9     a[3][0] = 1;
10     for (i = 4; i <= 100; i++)
11     {
12         length = a[i - 1][0];
13         carry = 0;
14         //handle multipling
15         for (j = 1; j <= length; j++)
16         {
17             carry += a[i - 1][j] * (4 * i - 2);
18             a[i][j] = carry % 10;
19             carry /= 10;
20         }
21         //determine the length
22         while (carry)
23         {
24             a[i][length++] = carry % 10;
25             carry /= 10;
26         }
27         remainder = 0;
28         //handle dividing
29         for (j = length; j >= 1; j--)
30         {
31             remainder = remainder * 10 + a[i][j];
32             a[i][j] = remainder / (i + 1);
33             remainder %= (i + 1);
34         }
35         //determine the length
36         while (!a[i][length])
37         {
38             length--;
39         }
40         a[i][0] = length;
41     }
42 }
43 int main()
44 {
45     int num, i;
46     catalan();
47     while (scanf("%d", &num) != EOF)
48     {
49         if (num < 4)
50             printf("%d\n", a[num][1]);
51         else
52         {
53             for (i = a[num][0]; i >= 1; i--)
54             {
55                 printf("%d", a[num][i]);
56             }
57             puts("");
58         }
59     }
60     return 0;
61 }

Key points

firstly, you must realize that it's a calatan question. Then you can solve it.

转载于:https://www.cnblogs.com/chuanlong/archive/2012/11/05/2756164.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值