1. 程式人生 > >51nod 1412 AVL樹的種類(經典dp)

51nod 1412 AVL樹的種類(經典dp)

cnblogs open mil 乘法 return mage ret avl樹 air

http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1412

題意:

技術分享

思路:

經典dp!!!可惜我想不到!!

$dp[i][k]$表示i個結點,最大深度為k的形態數。

它的轉移方程就是:

dp[i][k] += dp[i - 1 - j][k - 1] * dp[j][k - 1] 
dp[i][k] += 2 * dp[i - 1 - j][k - 2] * dp[j][k - 1]

j是右子樹結點個數,如果除去根結點,是不是可以分為左右兩棵子樹,那這裏就是應用了乘法原理。

分為兩種情況的原因是:①左右兩棵子樹的深度相同 ②左右兩棵子樹的深度差1,這裏左子樹深度小還是右子樹深度小都是一樣的,所以直接乘2即可。

 1 #include<iostream>
 2 #include<algorithm>
 3 #include<cstring>
 4 #include<cstdio>
 5 #include<sstream>
 6 #include<vector>
 7 #include<stack>
 8 #include<queue>
 9 #include<cmath>
10 #include<map>
11 #include<set>
12
using namespace std; 13 typedef long long ll; 14 typedef pair<int,ll> pll; 15 const int inf = 0x3f3f3f3f; 16 const int maxn=2000+5; 17 const int mod=1e9+7; 18 19 int n; 20 ll dp[maxn][20]; 21 22 void init() 23 { 24 dp[0][0]=1; 25 dp[1][1]=1; 26 for(int i=2;i<=2000;i++) 27
{ 28 for(int k=2;k<20;k++) 29 { 30 for(int j=0;j<i;j++) 31 { 32 dp[i][k]=(dp[i][k]+dp[i-1-j][k-1]*dp[j][k-1])%mod; 33 dp[i][k]=(dp[i][k]+2*dp[i-1-j][k-2]*dp[j][k-1])%mod; 34 } 35 } 36 } 37 } 38 39 int main() 40 { 41 //freopen("in.txt","r",stdin); 42 init(); 43 while(~scanf("%d",&n)) 44 { 45 ll ans=0; 46 for(int k=1;k<20;k++) 47 { 48 ans=(ans+dp[n][k])%mod; 49 } 50 printf("%lld\n",ans); 51 } 52 return 0; 53 }

51nod 1412 AVL樹的種類(經典dp)