链接
Description
有一棵苹果树,如果树枝有分叉,一定是分2叉(就是说没有只有1个儿子的结点)
这棵树共有N个结点(叶子点或者树枝分叉点),编号为1-N,树根编号一定是1。
我们用一根树枝两端连接的结点的编号来描述一根树枝的位置。下面是一颗有4个树枝的树
2 5
\ /
3 4
\ /
1
现在这颗树枝条太多了,需要剪枝。但是一些树枝上长有苹果。
给定需要保留的树枝数量,求出最多能留住多少苹果。
Input
第1行2个数,N和Q(1<=Q<= N,1
Output
一个数,最多能留住的苹果的数量。
Sample Input
5 2
1 3 1
1 4 10
2 3 20
3 5 20
Sample Output
21
思路:
首先这道题父亲和儿子有一定的联系,父亲的选择决定了儿子,我们可以用树形DP
设 t r e e [ x ] [ 1 ] tree[x][1] tree[x][1]为当前 x x x的左儿子, t r e e [ x ] [ 2 ] tree[x][2] tree[x][2]为当前 x x x的右儿子,然后用DFS一次枚举父亲节点和用循环枚举当前到 i i i这个点留给儿子有多少条边,于是 f [ i ] [ j ] f[i][j] f[i][j]表示以 i i i为节点的根保留 j j j条边的最大值,于是我们列出状态转移方程:
f [ v ] [ k ] = m a x ( f [ v ] [ k ] , ( f [ t r e e [ v ] [ 1 ] ] [ i ] + f [ t r e e [ v ] [ 2 ] ] [ k − i − 1 ] + n u m [ v ] ) ) f[v][k]=max(f[v][k],(f[tree[v][1]][i]+f[tree[v][2]][k-i-1]+num[v])) f[v][k]=max(f[v][k],(f[tree[v][1]][i]+f[tree[v][2]][k−i−1]+num[v]))
代码:
#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<queue>
#include<stack>
using namespace std;
int n, m;
int f[1000][1000], tree[1000][3];
int a[1000][1000], num[1000];
void VL_build(int x);
void VL_gress(int x, int y, int cnt)
{
num[y]=a[x][y];
tree[x][cnt]=y;
a[x][y]=a[y][x]=-1;
VL_build(y);
}
void VL_build(int x)
{
int cnt=0;
for(int i=0; i<=n; i++)
{
if(a[x][i]>=0)
{
cnt++;
VL_gress(x, i, cnt);
if(cnt==2) return;
}
}
}
void VL_dfs(int x, int k)
{
if(k==0)f[x][k]==0;
else if(tree[x][1]==0&&tree[x][2]==0)f[x][k]=num[x];
else
{
f[x][k]=0;
for(int i=0; i<k; i++)
{
if(f[tree[x][1]][i]==0)VL_dfs(tree[x][1], i);
if(f[tree[x][2]][k-i-1]==0)VL_dfs(tree[x][2], k-i-1);
f[x][k]=max(f[x][k], f[tree[x][1]][i]+f[tree[x][2]][k-i-1]+num[x]);
}
}
}
int main(){
scanf("%d%d", &n, &m);
for(int i=0; i<=n; i++)
for(int j=0; j<=n; j++)
a[i][j]=a[i][j]=-1;
for(int i=1; i<n; i++)
{
int x, y, xy;
scanf("%d%d%d", &x, &y, &xy);
a[x][y]=xy;
a[y][x]=xy;
}
VL_build(1);
VL_dfs(1, m+1);
printf("%d", f[1][m+1]);
return 0;
}