P2015 二叉苹果树(树形DP)

P2015 二叉苹果树

https://www.luogu.org/problemnew/show/P2015

题目描述

有一棵苹果树,如果树枝有分叉,一定是分2叉(就是说没有只有1个儿子的结点)

这棵树共有N个结点(叶子点或者树枝分叉点),编号为1-N,树根编号一定是1。

我们用一根树枝两端连接的结点的编号来描述一根树枝的位置。下面是一颗有4个树枝的树

2   5
 \ / 
  3   4
   \ /
    1

现在这颗树枝条太多了,需要剪枝。但是一些树枝上长有苹果。

给定需要保留的树枝数量,求出最多能留住多少苹果。

输入输出格式

输入格式:

 

第1行2个数,N和Q(1<=Q<= N,1<N<=100)。

N表示树的结点数,Q表示要保留的树枝数量。接下来N-1行描述树枝的信息。

每行3个整数,前两个是它连接的结点的编号。第3个数是这根树枝上苹果的数量。

每根树枝上的苹果不超过30000个。

 

输出格式:

 

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

 

输入输出样例

输入样例#1: 
5 2
1 3 1
1 4 10
2 3 20
3 5 20
输出样例#1: 
21
思路:树形DP好题
 1 import java.util.ArrayList;
 2 import java.util.Scanner;
 3 
 4 class node{
 5     int v;
 6     int w;
 7 }
 8 public class 树形DP {
 9     static int n,q;
10     static int [][] dp = new int [110][110];//dp[i][j]表示以i为根节点选j个树枝的最大值
11     static ArrayList<node> g[] = new ArrayList[110];
12     static void dfs(int x,int fa){
13         for(int i=0;i<g[x].size();i++){
14             node now = new node();
15             now = g[x].get(i);
16             int to = now.v;
17             int w = now.w;
18             if(to==fa)
19                 continue;
20             dfs(to, x);//先深搜到叶子节点 然后回推
21             for(int j=q;j>=0;j--){
22                 for(int k=0;k<=j-1;k++){//子树最多选j-1条树枝 因为必须选该子树和根节点连接的那一个枝子
23                     dp[x][j] = Math.max(dp[x][j], dp[x][k]+dp[to][j-k-1]+w);
24                 }
25             }
26         }
27     }
28     public static void main(String[] args) {
29         Scanner cin = new Scanner(System.in);
30         n = cin.nextInt();
31         q = cin.nextInt();
32         for(int i=0;i<=n;i++)
33             g[i] = new ArrayList<node>();
34         int a,b,c;
35         for(int i=0;i<n-1;i++){
36             a = cin.nextInt();
37             b = cin.nextInt();
38             c = cin.nextInt();
39             node tmp = new node();
40             tmp.v = b;
41             tmp.w = c;
42             g[a].add(tmp);
43             node tmp2 = new node();
44             tmp2.v = a;
45             tmp2.w = c;
46             g[b].add(tmp2);
47         }
48         dfs(1,0);
49         System.out.println(dp[1][q]);
50     }
51 }

 

posted @ 2019-02-25 17:19  *starry*  阅读(235)  评论(0编辑  收藏  举报