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
分析:
题意:
给你从1~n这n个整数,问分别用这n个数做根节点构建二叉搜索树,能有多少种构建二叉搜索树的方法?
解析:
看到给出的样例输入和输出,有点像卡塔兰数,又写了n=4的情况,还是与卡塔兰数符合,卡塔兰数的前几项分别是:
N | 对应卡塔兰数的值 |
---|---|
1 | 1 |
2 | 2 |
3 | 5 |
4 | 14 |
5 | 42 |
6 | 132 |
7 | 429 |
8 | 1430 |
9 | 4862 |
10 | 16796 |
越看越像卡塔兰数,我就把昨晚的HDU1023的代码提交了上去试试,果然过了!
实话说,我也不知道这个题为啥卡塔兰数,看着像就写完了!!!
代码:
#include<iostream>
#include<cstdio>
#define N 105
using namespace std;
int dp[N][N];
int main()
{
int n;
dp[1][0]=dp[1][1]=1;
for(int i=2;i<=100;i++)
{
int len=dp[i-1][0],v=0;
int k=(4*i-2);
for(int j=1;j<=len;j++)
{
dp[i][j]=k*dp[i-1][j]+v;
v=dp[i][j]/10;
dp[i][j]%=10;
}
while(v)
{
dp[i][++len]=v%10;
v/=10;
}
for(int j=len;j>0;j--)
{
v=v*10+dp[i][j];
dp[i][j]=v/(i+1);
v%=(i+1);
}
while(!dp[i][len])
{
len--;
}
dp[i][0]=len;
}
while(~scanf("%d",&n))
{
for(int i=dp[n][0];i>0;i--)
{
printf("%d",dp[n][i]);
}
printf("\n");
}
return 0;
}