CodeForces 9 D.How many trees?(dp)
2017-12-23 10:54
309 查看
Description
求n个节点构成的高度不小于h的二叉树数量
Input
两个整数n,h(1≤h≤n≤35)
Output
输出n个节点构成的高度不小于h的二叉树数量
Sample Input
3 2
Sample Output
5
Solution
dp[n][h]表示n个节点构成的高度为h的二叉树数量,枚举左儿子节点数量x和高度h1以及右儿子高度h2,则右儿子节点数量为n−1−x,进而有转移方程dp[n][h]=∑h1,h2,xdp[x][h1]∗dp[n−1−x][h2],记忆化一下即可
Code
求n个节点构成的高度不小于h的二叉树数量
Input
两个整数n,h(1≤h≤n≤35)
Output
输出n个节点构成的高度不小于h的二叉树数量
Sample Input
3 2
Sample Output
5
Solution
dp[n][h]表示n个节点构成的高度为h的二叉树数量,枚举左儿子节点数量x和高度h1以及右儿子高度h2,则右儿子节点数量为n−1−x,进而有转移方程dp[n][h]=∑h1,h2,xdp[x][h1]∗dp[n−1−x][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 [h])return dp [h]; flag [h]=1; if(n==h) { if(n==0)return dp [h]=1; return dp [h]=1ull<<(n-1); } if(((1ll<<h)-1<n)||n<h)return dp [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 [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; }
相关文章推荐
- Codeforces Beta Round #9 (Div. 2 Only) D. How many trees? dp
- #9 (Div. 2 Only) D. How many trees? (dp)(好题)
- Codeforces Beta Round #9 (Div. 2 Only) D. How many trees? dp
- CF 9D. How many trees?(dp)
- Codeforces Beta Round #9 (Div. 2 Only) D. How many trees? dp
- Codeforces_9D_How many trees?
- Codeforces Beta Round #9 (Div. 2 Only), problem: (D) How many trees? DP
- Codeforces_9D-How many trees?
- hdu 1130 How Many Trees?(Catalan数)
- LightOJ 1140 How Many Zeroes?(数位dp)
- HDU 1978 How many ways(DP)
- poj2029--Get Many Persimmon Trees(dp)
- UVA 10303 How Many Trees? (catlan)
- How many ways-dp
- poj 2029 Get Many Persimmon Trees(dp)
- 杭电1130How Many Trees?
- CodeForces - 711C Coloring Trees(DP)(思维)
- How Many Trees?[HDU1130]
- hdu1978——How many ways(记忆化dp)
- LightOJ - 1140 How Many Zeroes?(数位DP,有前导0)