【DP】【CF9D】 How many trees?

传送门

Description

给你两个正整数\(n,h\),求由\(n\)个点组成的高度大于等于\(h\)的二叉树有多少个

Input

一行两个整数\(n,h\)

Output

一个整数代表答案。

Hint

\(For~All:\)

\(0~\leq~h~\leq~n~\leq~35\)

Solution

数数题,考虑递推。发现高度\(h\)可以作为阶段,于是设计\(f_{i,j}\)为用\(i\)个点做出高度大于等于\(j\)的二叉树,发现无法转移。考虑更换状态。设\(f_{i,j}\)为用\(i\)个点做出高度小于等于\(j\)的二叉树的答案。发现左右子树互不影响,可以乘法原理。

于是可以转移了。最后减一下就是答案

Code

#include<cstdio>
#define rg register
#define ci const int
#define cl const long long int

typedef long long int ll;

namespace IO {
    char buf[90];
}

template<typename T>
inline void qr(T &x) {
    char ch=getchar(),lst=' ';
    while(ch>'9'||ch<'0') lst=ch,ch=getchar();
    while(ch>='0'&&ch<='9') x=(x<<1)+(x<<3)+(ch^48),ch=getchar();
    if(lst=='-') x=-x;
}

template<typename T>
inline void qw(T x,const char aft,const bool pt) {
    if(x<0) x=-x,putchar('-');
    int top=0;
    do {
        IO::buf[++top]=x%10+'0';
        x/=10;
    } while(x);
    while(top) putchar(IO::buf[top--]);
    if(pt) putchar(aft);
}

template<typename T>
inline T mmax(const T a,const T b) {return a > b ? a : b;}
template<typename T>
inline T mmin(const T a,const T b) {return a < b ? a : b;}
template<typename T>
inline T mabs(const T a) {return a < 0 ? -a : a;}

template<typename T>
inline void mswap(T &a,T &b) {
    T temp=a;a=b;b=temp;
}

const int maxn  = 40;

int n,h;
ll frog[maxn][maxn];

int main() {
    qr(n);qr(h);
    for(rg int i=0;i<=n;++i) frog[0][i]=1;
    for(rg int i=1;i<=n;++i) {
        for(rg int j=1;j<=n;++j) {
            for(rg int k=0;k<j;++k) {
                frog[j][i]+=frog[k][i-1]*frog[j-k-1][i-1];
            }
        }
    }
    qw(frog[n][n]-frog[n][h-1],'\n',true);
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/yifusuyi/p/9820450.html