Codeforces 9D How many trees? 【计数类DP】

版权声明:欢迎转载,请注明出处,谢谢 https://blog.csdn.net/Dream_maker_yk/article/details/82085386

Codeforces 9D How many trees?


LINK


题目大意就是给你一个n和一个h

问你有多少个n个节点高度不小于h的二叉树


n和h的范围都很小

感觉有无限可能

考虑一下一个很显然的DP

d p n , h n h

然后考虑咋转移

首先我们可以肆无忌惮地,枚举一下,因为左右子树的高度至少有一个是h-1,所以我们需要枚举一个子树的大小和另一个子树的高,但是我们发现,当左右两个子树的高度相等的时候贡献会统计两次,减掉一次贡献就行了


#include<bits/stdc++.h>
using namespace std;
#define N 50
#define LL long long
#define fu(a,b,c) for(int a=b;a<=c;++a)
#define fd(a,b,c) for(int a=b;a>=c;--a)
LL dp[N][N];
int n,h;
int main(){
    scanf("%d%d",&n,&h);
    dp[0][0]=1;
    fu(i,1,n)
        fu(j,0,n)
            fu(k,0,j-1){
                fu(p,0,i-1)dp[i][j]+=2ll*dp[i-1][k]*dp[p][j-k-1];
                dp[i][j]-=dp[i-1][k]*dp[i-1][j-k-1];
            }
    LL ans=0;
    fu(i,h,n)ans+=dp[i][n];
    printf("%lld",ans);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Dream_maker_yk/article/details/82085386