Codeforces Beta Round #9 (Div. 2 Only) D. How many trees? dp
题目链接:
http://www.codeforces.com/contest/9/problem/D
D. How many trees?
memory limit per test64 megabytes
题意
问你节点数为n,树高>=h的二叉搜索树有多少种
代码
#include<map>
#include<set>
#include<cmath>
#include<queue>
#include<stack>
#include<ctime>
#include<vector>
#include<cstdio>
#include<string>
#include<bitset>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<functional>
using namespace std;
#define X first
#define Y second
#define mkp make_pair
#define lson (o<<1)
#define rson ((o<<1)|1)
#define mid (l+(r-l)/2)
#define sz() size()
#define pb(v) push_back(v)
#define all(o) (o).begin(),(o).end()
#define clr(a,v) memset(a,v,sizeof(a))
#define bug(a) cout<<#a<<" = "<<a<<endl
#define rep(i,a,b) for(int i=a;i<(b);i++)
#define scf scanf
#define prf printf
typedef __int64 LL;
typedef vector<int> VI;
typedef pair<int,int> PII;
typedef vector<pair<int,int> > VPII;
const int INF=0x3f3f3f3f;
const LL INFL=0x3f3f3f3f3f3f3f3fLL;
const double eps=1e-8;
const double PI = acos(-1.0);
//start----------------------------------------------------------------------
const int maxn=44;
//dp[i][j]表示节点数为i,高度至少为j的搜索二叉树有多少种。
//dp2[i]表示节点数为i的二叉树有多少颗。
LL dp[maxn][maxn],dp2[maxn];
int n,h;
int main() {
clr(dp2,0);
dp2[0]=dp2[1]=1;
for(int i=2;i<maxn;i++){
//枚举根节点
for(int k=1;k<=i;k++){
dp2[i]+=dp2[k-1]*dp2[i-k];
}
}
clr(dp,0);
dp[0][0]=1;
for(int i=1;i<maxn;i++){
for(int j=0;j<maxn;j++){
if(j<=1){
dp[i][j]=dp2[i];
continue;
}
//枚举根节点为k
for(int k=1;k<=i;k++){
//这里容斥一下
dp[i][j]+=dp2[k-1]*dp[i-k][j-1];
dp[i][j]+=dp[k-1][j-1]*dp2[i-k];
dp[i][j]-=dp[k-1][j-1]*dp[i-k][j-1];
}
}
}
scf("%d%d",&n,&h);
prf("%I64d\n",dp[n][h]);
return 0;
}
//end-----------------------------------------------------------------------