You're given a tree with weights of each node, you need to find the maximum subtree of specified size of this tree.
Tree Definition
A tree is a connected graph which contains no cycles.
Input
There are several test cases in the input.
The first line of each case are two integers N(1 <= N <= 100), K(1 <= K <= N), where N is the number of nodes of this tree, and K is the subtree's size, followed by a line with N nonnegative integers, where the k-th integer indicates the weight of k-th node. The following N - 1 lines describe the tree, each line are two integers which means there is an edge between these two nodes. All indices above are zero-base and it is guaranteed that the description of the tree is correct.
Output
One line with a single integer for each case, which is the total weights of the maximum subtree.
Sample Input
3 1 10 20 30 0 1 0 2 3 2 10 20 30 0 1 0 2
Sample Output
30 40
Author: LIU, Yaoting
Source: ZOJ Monthly, May 2009
这份题解现在看起来感觉好幼稚,就是一个简单的树形背包啊(2016/10/25):
题意是给出一棵树,每个点都有权值,现在需要求有k个结点的子树的最大权值。
dp[i][j]表示序号为i的根节点,形成的节点数为j的"子树"的权值和
首先题目中的子树跟我们平时的子树不一样,他的子树就是一块连通的点集,其中子树有根节点,假如选了某个节点,可以不选它的子节点。
状态转移方程:dp[x][all]=max{ dp[x][j]+dp[y][all-j] } 其中x表示根节点为x, y表示新考虑的子节点
dp[i][j]表示序号为i的根节点,形成的节点数为j的"子树"的权值和
#include<cstdio>
#include<iostream>
#include<cmath>
#include<cstring>
#include<climits>
#include<string>
#include<algorithm>
#include<queue>
#include<set>
#include<vector>
#include<map>
#include<stack>
//typedef __int64 ll;
// %I64d
//by yskyskyer123
using namespace std;
const int maxn=100+10;
int a[maxn];
int n,k;
vector<int >nex[maxn];
int dp[maxn][maxn];//dp[i][j]表示序号为i的根节点,形成的节点数为j的"子树"的权值和
bool vis[maxn];
void DP(int x)
{
dp[x][1]=a[x]; //首先,根节点为x,节点数为1的子树,只有1个节点,就是自身,权值和就是他自己的权值
for(int i=0;i<nex[x].size();i++)//一开始只考虑有节点x,慢慢一个一个加入x的子节点,进行动态规划。
{
int y=nex[x][i];
if(vis[y]) continue;
vis[y]=1;
DP(y);
for(int all=k;all>=1;all--)/*<span style="color:#ff0000;">状态转移方程:dp[x][all]=max{ dp[x][j]+dp[y][all-j] } 其中x表示根节点为x,y表示新考虑的子节点</span>
(且已经考虑了一些子节点,每次i+1,dp[x][k]的值都会更新为考虑了新节点后的值)*/
/*考虑到计算dp[x][all]由dp[x][j]+dp[y][all-j]决定,而为了让dp[x][j]表示不考虑子节点nex[x][i]的情形。
all的顺序必须从k到1*/
{
for(int ori=1;ori<=all;ori++)//ori表示不考虑nex[x][i]时子树节点个数
{
dp[x][all]=max(dp[x][ori]+dp[y][all-ori ] ,dp[x ][all]);
}
}
}
}
int main()
{
int i,j,x,y;
while(~scanf("%d%d",&n,&k))
{
for(int i=0;i<n;i++)
{
nex[i].clear();
scanf("%d",&a[i]);
for(int j=1;j<=k;j++)
{
dp[i][j]=0;
}
}
for(int i=1;i<=n-1;i++)
{
scanf("%d%d",&x,&y);
nex[x].push_back(y);
nex[y].push_back(x);
}
memset(vis,0,sizeof vis);
vis[0]=1;
DP(0);
int ans=0;
for(int i=0;i<n;i++)
ans=max(ans,dp[i][k]);
printf("%d\n",ans);
}
}