CodeForces 9 D.How many trees?(dp)

来源:互联网 发布:php socket可以做什么 编辑:程序博客网 时间:2024/05/17 00:17

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;}