2015
05-23

# Easy Tree DP?

A Bear tree is a binary tree with such properties : each node has a value of 20,21…2(N-1)(each number used only once),and for each node ,its left subtree’s elements’ sum<its right subtree’s elements’ sum(if the node hasn’t left/right subtree ,this limitation is invalid).
You need to calculate how many Bear trees with N nodes and exactly D deeps.

First a integer T(T<=5000),then T lines follow ,every line has two positive integer N,D.(1<=D<=N<=360).

First a integer T(T<=5000),then T lines follow ,every line has two positive integer N,D.(1<=D<=N<=360).

2
2 2
4 3

Case #1: 4
Case #2: 72

5000个测试点，n,d<=360

1.首先注意f[n][d]的结果是一定的，所以先预处理出来所有的f[n][d]。然后对每个测试点直接输出f[n][d]即可。（一开始一直T就是因为没有预处理）

2.由于2^i的特殊性质，题目中有一个条件可以转化：左子树和<右子树和等价于左子树最大值<右子树最大值。

3.f[i][j]表示i个节点组成深度不超过j的满足条件的二叉树个数，则最后答案是(f[n][d]+maxmod-f[n][d-1])%maxmod。（注意在反复取余后最后结果f[n][d]可能会小于f[n][d-1]）

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
using namespace std;
const int maxn=369;
const long long maxmod=1000000000+7;
long long f[maxn][maxn],c[maxn][maxn];
int n,m,z,sec;
int main()
{
memset(f,0,sizeof(f));
memset(c,0,sizeof(c));
for(int i=1;i<=360;i++)
{
c[0][0]=1;
c[i][0]=1;
}
for(int i=1;i<=360;i++)
for(int j=1;j<=i;j++)
c[i][j]=(c[i-1][j-1]+c[i-1][j])%maxmod;
for(int j=1;j<=360;j++)
f[1][j]=1;
for(int i=2;i<=360;i++)
for(int j=1;j<=360;j++)
{
f[i][j]=(c[i][i-1]*2*f[i-1][j-1])%maxmod;
for(int k=1;k<=i-2;k++)
f[i][j]=(f[i][j]+((c[i][i-1]*c[i-2][k])%maxmod)*((f[k][j-1]*f[i-1-k][j-1])%maxmod))%maxmod;
}
scanf("%d",&sec);
for(int z=1;z<=sec;z++)
{
scanf("%d%d",&n,&m);
printf("Case #%d: %I64d\n",z,(f[n][m]+maxmod-f[n][m-1])%maxmod);
}
return 0;
}