How Many Trees?_BST递推_2018_2_20

10 篇文章 0 订阅
1 篇文章 0 订阅
How Many Trees?

Time Limit: 2 Seconds      Memory Limit: 65536 KB

The balanced binary tree is defined recursively as follows:

1. The difference in the depth of its left child tree and right child tree is at most 1.

2. Its left child tree is a balanced binary tree.

3. Its right child tree is also a balanced binary tree.

Now it is your job to calculate the number of balanced binary trees with given number of nodes and leaves.


Input

The input consists of multiple tests. Each test consists of 2 numbers n and m in a single line, the number of the nodes and the number of leaves. (0 < m <= n <= 20)


Output

The number of balanced binary trees which have exactly n nodes and m leaves.


Sample Input

5 2
15 9


Sample Output

4
0



Author: TANG, Jiqing

Source: ZOJ Monthly, December 2002

#include<iostream>
#include<cstdio>
using namespace std;
typedef long long ll;
ll d[21][21][15];

ll solve(int n,int m,int k){
	ll ans=0;
	for(int i=0;i<n;i++)
	for(int j=0;j<=m;j++){
		ans+=d[i][j][k-2]*d[n-1-i][m-j][k-1];
		ans+=d[i][j][k-1]*d[n-1-i][m-j][k-1];
		ans+=d[i][j][k-1]*d[n-1-i][m-j][k-2];
	}
	return ans;
}

int main(){
	d[1][1][1]=d[0][0][0]=1;
	for(int i=2;i<=20;i++)
	for(int j=1;j<=i;j++)
	for(int k=2;k<=7;k++){
		d[i][j][k]=solve(i,j,k);
		//printf("%d %d %d %d\n",i,j,k,d[i][j][k]);
	}
	int n,m;
	while(~scanf("%d%d",&n,&m)){
		ll ans=0;
		for(int i=1;i<=7;i++)
		ans+=d[n][m][i];
		printf("%d\n",ans);
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值