Problem: 二叉苹果树

Problem: 二叉苹果树

Time Limit: 1 Sec Memory Limit: 128 MB
[Submit][Status][Web Board]

Description

有一棵苹果树,如果树枝有分叉,一定是分2叉(就是说没有只有1个儿子的结点)。这棵树共有N个结点(叶子点或者树枝分叉点),编号为1-N,树根编号一定是1。我们用一根树枝两端连接的结点的编号来描述一根树枝的位置。下面是一颗有4个树枝的树:

   2   5
     /
     3   4
       /
       1

现在这颗树枝条太多了,需要剪枝。但是一些树枝上长有苹果。
给定需要保留的树枝数量,求出最多能留住多少苹果。注意树根不能剪没了哟。

Input

第1行2个数,N和Q(1<=Q<=N,I<N<=IOO)。
N表示树的结点数,Q表示要保留的树枝数量。
接下来N-I行描述树枝的信息。 每行3个整数,前两个是它连接的结点的编号。第3个数是这根树枝上苹果的数量。 每根树枝上的苹果不超过30000个。

Output

一个数,最多能留住的苹果的数量。

Sample Input

5 2
1 3 1
1 4 10
3 2 20
3 5 20

Sample Output

21

HINT

    2   5            2   5 
      /               *
      3   4   --->     3   4
        /               *
        1                1

题解

Code

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
struct edge {
	int next,to,w;
} e[1001];

int f[1001][1001]; //f[i][j]代表以i为根的子树中选出j个节点(不包括自身)时的最大价值
int head[101],cnt;

void add(int x,int y,int w)
{
	e[++cnt]=edge { head[x],y,w };
	head[x]=cnt;
}

int dfs(int x,int fa) //返回这个点为根的子树中节点的个数(不包括本身)
{
	int sum=0;
	for(int i=head[x]; i!=0; i=e[i].next)
	{
		if(e[i].to==fa) continue; //防止走到父节点
		sum+=dfs(e[i].to,x)+1;
		for(int j=sum; j>=1; j--) //类似背包 
			for(int k=1; k<=j; k++)
				f[x][j]=max(f[x][j],f[x][j-k]+f[e[i].to][k-1]+e[i].w);
	}
	return sum;
}

int main()
{
	int n,m;
	scanf("%d %d",&n,&m);
	for(int i=1,x,y,w; i<n; i++)
	{
		scanf("%d %d %d",&x,&y,&w);
		add(x,y,w);
		add(y,x,w);
	}
	dfs(1,0);
	printf("%d",f[1][m]); //以1为根保留m个节点的最大价值
	return 0;
}
原文地址:https://www.cnblogs.com/ZhaoChongyan/p/11740387.html