您的位置:首页 > 其它

CodeForces 9 D.How many trees?(dp)

2017-12-23 10:54 309 查看
Description

求n个节点构成的高度不小于h的二叉树数量

Input

两个整数n,h(1≤h≤n≤35)

Output

输出n个节点构成的高度不小于h的二叉树数量

Sample Input

3 2

Sample Output

5

Solution

dp[n][h]表示n个节点构成的高度为h的二叉树数量,枚举左儿子节点数量x和高度h1以及右儿子高度h2,则右儿子节点数量为n−1−x,进而有转移方程dp[n][h]=∑h1,h2,xdp[x][h1]∗dp[n−1−x][h2],记忆化一下即可

Code

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<queue>
#include<map>
#include<set>
#include<ctime>
using namespace std;
typedef unsigned long long ull;
typedef long long ll;
typedef pair<int,int>P;
const int maxn=40;
bool flag[maxn][maxn];
ull dp[maxn][maxn];
ull Solve(int n,int h)
{
if(flag
[h])return dp
[h];
flag
[h]=1;
if(n==h)
{
if(n==0)return dp
[h]=1;
return dp
[h]=1ull<<(n-1);
}
if(((1ll<<h)-1<n)||n<h)return dp
[h]=0;
ull ans=0;
for(int h1=0;h1<h;h1++)
for(int h2=0;h2<h;h2++)
if(max(h1,h2)==h-1)
for(int x=0;x<n;x++)
ans+=Solve(x,h1)*Solve(n-1-x,h2);
return dp
[h]=ans;
}
int main()
{
int n,h;
while(~scanf("%d%d",&n,&h))
{
ull ans=0;
for(int i=h;i<=n;i++)ans+=Solve(n,i);
printf("%I64u\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: