树形DP

#include <iostream>
#include <algorithm>
using namespace std;
int v[110],n,M;
int dp[110][110]={0};
bool is[110]={false},e[110][110]={false};
void postorder(int root)
{
	if(is[root]) return ;
	is[root]=true;
	for(int i=1;i<=n;i++) if(e[root][i])
		postorder(i);
	dp[root][1]=v[root];
	for(int t_child=1;t_child<=n;t_child++) if(e[root][t_child]&&!is[t_child]){
		for(int m=M;m>=2;m--)
			for(int m_child=1;m_child<m;m_child++)
				dp[root][m]=max(dp[root][m],dp[root][m-m_child]+dp[t_child][m_child]);
	}
	is[root]=false;
}
int main()
{
	cin>>n>>M;
	for(int i=1;i<=n;i++) cin>>v[i];
	for(int i=1;i<n;i++){
		int a,b;
		cin>>a>>b;
		e[a][b]=e[b][a]=true;
	}
	postorder(1);
	cout<<dp[1][M]<<endl;
	return 0;
}


  曾经看到过一个讲树形DP的文章说要将K-树转化为二叉树,其实是没必要的,我们只需要将其递推关系转化为背包问题或者其组合就可以解决了,采取后序遍历从树叶推根

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值