P2015 two fork Apple tree title description
There is an apple tree, if the branch has a fork, it must be divided into 2 forks (that is, there is no only 1 sons of the knot)
The tree has a total of N nodes (leaf Point or Branch fork Point), numbered 1-n, the root number must be 1.
We describe the position of a branch with the number of nodes connected at each end of a branch. Here's a tree with 4 branches.
2 5 \/3 4 \/1 Now this branch is too much to be pruned. But some branches have apples on them.
Given the number of branches that need to be retained, find out how many apples you can keep.
Input output Format input format:
The 1th line is 2 digits, N and Q (1<=q<= n,1<n<=100).
n represents the number of nodes in the tree, and Q indicates how many branches to keep. Next, the N-1 line describes the information of the branch.
3 integers per line, the first two being the number of nodes to which it is connected. The 3rd number is the number of apples on this branch.
There are no more than 30,000 apples on each branch.
Output format:
A number, the maximum number of apples that can be retained.
Input and Output sample input sample #: Copy
5 21 3 11 4 102 3 203 5 20
Output Example # #: Replication
21st
Analysis
>:< the first tree-shaped motion, to commemorate!!!
Tree-shaped motion, + backpack
If you want to keep the next branch A, then first leave A's father's branch.
So: Dp[u][j] The maximum value of J (which must be Unicom) is left in the subtree with U as root.
Then push from leaf to root.
Transfer equation: dp[u][j] = max (dp[u][j],dp[v][k]+dp[u][j-k-1]+w);
is to select the K-branches from the subtree V, select the J-k-1 bar from the other subtree of the U-Tree, and combine the one that connects V to the maximum value of the J-Bar selected from the tree U.
Code
1#include <cstdio>2#include <algorithm>3#include <cstring>4 5 using namespacestd;6 7 Const intN = the;8 9 structedge{Ten intto,nxt,w; One}e[10010]; A inthead[10010],tot; - - intDp[n][n]; the intsum,n,m; - -InlineintRead () { - intx =0, F =1;CharCH =GetChar (); + for(; ch<'0'|| Ch>'9'; CH =GetChar ()) - if(ch=='-') F =-1; + for(; ch>='0'&ch<='9'; CH =GetChar ()) Ax = x*Ten+ch-'0'; at returnx*F; - } - -InlinevoidAdd_edge (intUintVintW) { -e[++tot].to = V,E[TOT].W = W,E[TOT].NXT = Head[u],head[u] =tot; - } in - voidDfsintUintFA) { to for(intI=head[u]; I I=e[i].nxt) { + intv = e[i].to,w =E[I].W; - if(V==FA)Continue; the DFS (v,u); * for(intJ=m; j>=1; --j) $ for(intk=0; k<j; ++k)Panax NotoginsengDP[U][J] = max (dp[u][j],dp[v][k]+dp[u][j-k-1]+W); - } the } + intMain () { A then = Read (), M =read (); + for(intA,b,c,i=1; i<n; ++i) { -A = read (), B = Read (), C =read (); $ Add_edge (a,b,c), Add_edge (b,a,c); $ } - -Dfs1,0); theprintf"%d", dp[1][m]); - Wuyi return 0; the}
P2015 two-prong apple tree