1. 程式人生 > >【BZOJ3769】spoj 8549 BST again DP(記憶化搜索?)

【BZOJ3769】spoj 8549 BST again DP(記憶化搜索?)

ret lin 多少 sam 16px char long long cst ini

【BZOJ3769】spoj 8549 BST again

Description

求有多少棵大小為n的深度為h的二叉樹。(樹根深度為0;左右子樹有別;答案對1000000007取模)

Input

第一行一個整數T,表示數據組數。 以下T行,每行2個整數n和h。

Output

共T行,每行一個整數表示答案(對1000000007取模)

Sample Input

2
2 1
3 2

Sample Output

2
4

HINT

對於100%的數據,1<=n<=600,0<=h<=600,1<=T<=10

題解:直接列DP方程,設f[i][j]表示有i個節點,深度為j的二叉樹個數,然後列出方程用前綴和優化轉移即可(註意防重)。

然後光榮TLE了,正解貌似是記憶化搜索?不過懶得改了,卡了卡常數就過了。

#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;
typedef long long ll;
const int P=1000000007;
int n,m;
int a[15],b[15];
int f[610][610],s[610][610];
inline int rd()
{
	int ret=0,f=1;	char gc=getchar();
	while(gc<‘0‘||gc>‘9‘)	{if(gc==‘-‘)f=-f;	gc=getchar();}
	while(gc>=‘0‘&&gc<=‘9‘)	ret=ret*10+gc-‘0‘,gc=getchar();
	return ret*f;
}
void init()
{
	register int i,j,k;
	f[0][0]=s[0][0]=1;
	for(j=1;j<=m;j++)	s[0][j]=1;
	for(i=1;i<=n;i++)	for(j=1;j<=m;j++)
	{
		if(i>=j)	for(k=0;k<i;k++)	f[i][j]=(f[i][j]+(ll)f[k][j-1]*s[i-k-1][j-1]+(ll)s[k][j-2]*f[i-k-1][j-1])%P;
		s[i][j]=(s[i][j-1]+f[i][j])%P;
	}
}
int main()
{
	int i,T=rd();
	for(i=1;i<=T;i++)	a[i]=rd(),b[i]=rd()+1,n=max(n,a[i]),m=max(m,b[i]);
	init();
	for(i=1;i<=T;i++)	printf("%d\n",f[a[i]][b[i]]);
	return 0;
}

【BZOJ3769】spoj 8549 BST again DP(記憶化搜索?)