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
题意:给一颗无根树,每个点有权值,要找出一个子树,点数为k,并且使得k个点的权值和最大。
定1为根
定义dp[u][m],以u为根的子树下,包含m个点的最小权值。因为每个点都可能作为最后那个子树的根,所以枚举所有的dp[u][m],找出最大的那个值
ANS = max(ANS,dp[u][m]);
考虑转移,因为是以u为根的子树,所以u这个点是必须选的,然后考虑u下面的子树怎么选,这就是个背包问题。u下面的第1个子树选了k1个点,第2个子树选了k2个点,第3个子树选了k3个点……最后使得总权值和最大
dp[u][m] = max(dp[u][m] , dp[u][m-i] + dp[v][i]);
#include <iostream>
#include <algorithm>
#include <cmath>
#include <ctype.h>
#include <cstring>
#include <cstdio>
#include <sstream>
#include <cstdlib>
#include <iomanip>
#include <string>
#include <queue>
#include <map>
#include <vector>
using namespace std;
const int maxn=105;
vector<int> tree[maxn];
int n,k;
int dp[maxn][maxn];
int vis[maxn];//标记是否被访问
int Maxn;
void dfs(int u)
{
vis[u]=1;
for(int i=0;i<tree[u].size();i++)
{
int v=tree[u][i];
if(!vis[v])
{
dfs(v);
for(int j=k;j>=1;j--)
for(int m=1;m<j;m++)
dp[u][j]=max(dp[u][j],dp[u][m]+dp[v][j-m]);
}
}
}
int main()
{
while(scanf("%d%d",&n,&k)!=EOF)
{
Maxn=0;
for(int i=0;i<n;i++)
tree[i].clear();
memset(dp,0,sizeof(dp));
memset(vis,0,sizeof(vis));
for(int i=0;i<n;i++)
scanf("%d",&dp[i][1]);
for(int i=0;i<n-1;i++)
{
int u,v;
scanf("%d%d",&u,&v);
tree[u].push_back(v);
tree[v].push_back(u);
}
dfs(0);
for(int i=0;i<n;i++)
{
if(dp[i][k]>Maxn)
Maxn=dp[i][k];
}
printf("%d\n",Maxn);
}
}