CodeForces 9 D.How many trees?(dp)

202 篇文章 1 订阅

Description

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

Input

两个整数 n,h(1hn35)

Output

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

Sample Input

3 2

Sample Output

5

Solution

dp[n][h] 表示 n 个节点构成的高度为h的二叉树数量,枚举左儿子节点数量 x 和高度h1以及右儿子高度 h2 ,则右儿子节点数量为 n1x ,进而有转移方程 dp[n][h]=h1,h2,xdp[x][h1]dp[n1x][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[n][h])return dp[n][h];
    flag[n][h]=1;
    if(n==h)
    {
        if(n==0)return dp[n][h]=1;
        return dp[n][h]=1ull<<(n-1);
    }
    if(((1ll<<h)-1<n)||n<h)return dp[n][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[n][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;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值