https://www.luogu.org/problem/show?pid=2015 Topic 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 example # #:
5 21 3 11 4 102 3 203 5 20
Sample # # of output:
21st
F[I][J] indicates that node I retains the maximum number of apples that can be obtained by J branches
1#include <cstdio>2 3InlinevoidReadint&x)4 {5x=0; RegisterCharCh=GetChar ();6 for(; ch>'9'|| ch<'0'; ) ch=GetChar ();7 for(; ch>='0'&&ch<='9'; Ch=getchar ()) x=x*Ten+ch-'0';8 }9 Const intN the);Ten intHead[n],sumedge; One structEdge { A intV,w,next; -Edge (intv=0,intnext=0,intw=0): - V (v), next (Next), W (w) {} the}edge[n<<1]; -InlinevoidInsintUintVintW) - { -edge[++sumedge]=Edge (v,head[u],w); +head[u]=Sumedge; -edge[++sumedge]=Edge (u,head[v],w); +head[v]=Sumedge; A } at - #defineMin (A, b) (A<B?A:B) - #defineMax (A, B) (A>B?A:B) - - intN,q,f[n][n]; - intDFS (intUintFA) in { - intsum=0; to for(intV,i=head[u]; I I=edge[i].next) + { -v=edge[i].v; the if(V==FA)Continue; *Sum+=dfs (V,u) +1; $ for(intJ=min (SUM,Q); J --j)Panax Notoginseng for(intk=0; k<j; ++k) -F[u][j]=max (f[u][j],f[u][j-k-1]+f[v][k]+EDGE[I].W); the } + returnsum; A } the + intpresist () - { $ read (n), read (q); $ for(intU,v,w,i=1; i<n; ++i) - Read (U), read ( v), read (W), INS (u,v,w); -DFS (1,0); theprintf"%d\n", f[1][q]); - return 0;Wuyi } the - intAptal=presist (); Wu intMain () {;}
Rokua--p2015 two fork apple tree