DP-- binary tree apple tree

Binary apple tree

There are a binary apple, if there is forked branches, must be bifurcated, that there is only one son node.

This tree total of N nodes, numbered 1 to N, the root of a certain number.

We use a branch node connected to both ends of a branch number description position.

Apple tree branches too much, need pruning. But some of the branches grow apples, given the need to retain a number of branches, seeking to keep up to how many apples.

Here Reserved means the final station 1 communicates with.

Input format
The first line contains two integers N and Q, respectively, and the number of nodes in the tree branches to be retained.

Next, N-1 branch line description information, each row of three integers, the first two is the number of nodes connected to it, the third number is the number of the limb and apples.

Output format
output line only indicates the number up to keep the apple.

Data range
1 ≦ q <N≤100.
N ≠. 1,
on each branch Apple not more than 30,000.

Sample input:
. 5 2
. 1. 3. 1
. 1. 4 10
2 20 is. 3
. 3. 5 20 is
a sample output:
21

answer:

There are a bit like a backpack dependent herein do with DP tree, we use the f [i] [j] i is expressed in root weight retention and m edges.
So we traverse every node in the tree run again backpack on it.

#include<bits/stdc++.h>
using namespace std;
const int N=105,M=N*2;
int f[N][N],m,n,ne[M],h[M],e[M],w[M],cnt,ans;
void add(int a,int b,int c)
{
	e[cnt]=b,w[cnt]=c,ne[cnt]=h[a],h[a]=cnt++;
}
void dfs(int u,int fa)
{
	for(int i=h[u];i!=-1;i=ne[i]){
		if(e[i]==fa) continue;
		dfs(e[i],u);
		for(int j=m;j>=0;j--){
			for(int k=0;k<j;k++){
				f[u][j]=max(f[u][j],f[u][j-k-1]+f[e[i]][k]+w[i]);
			}
		}
	}
}
int main()
{
	cin>>n>>m;
	memset(h,-1,sizeof h);
	for(int i=1;i<n;i++){
		int a,b,c; cin>>a>>b>>c;
		add(a,b,c),add(b,a,c);
	}
	dfs(1,-1);
	cout<<f[1][m]<<endl;
}
Published 92 original articles · won praise 6 · views 1163

Guess you like

Origin blog.csdn.net/weixin_42979819/article/details/103947666