[Luogu2015] 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 there are too many branches to prune. 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/Output sample
Input Sample # #:
5 2
1 3 1
1 4 10
2 3 20
3 5 20
Sample # # of output:
21st
A tree DP of the topic of the comparison of water
\ (f[i][j]\) represents the i\ node, under which the maximum number of apples obtained by \ (j\) branches is retained.
To shift from bottom to top:
\[f[i][j]=f[son1][x]+f[son2][y]+ (V[son1]) + (V[son2]) \]
\ (x+y=\) \ (j-2\) or \ (j-1\) or \ (j\), discuss it.
See the code specifically.
#include <cstring>#include <algorithm>#include <cstdio>#include <iostream>using namespaceStdintRead () {intx=0, w=1;CharCh=getchar (); while(ch>' 9 '|| ch<' 0 ') {if(ch=='-') w=-1; Ch=getchar ();} while(ch>=' 0 '&&ch<=' 9 ') x= (x<<3) + (x<<1) +ch-' 0 ', Ch=getchar ();returnX*w;}intn,q,cnt;inthead[ the];intdp[ the][ the];intson[ the][2];intw[ the][2];structnode{intV,to,next;} edge[ About];voidAddintXintYintz) {cnt++; Edge[cnt].to=y; EDGE[CNT].NEXT=HEAD[X]; Edge[cnt].v=z; head[x]=cnt;}voidDfsint,int);intMain () {intX, Y, Z N=read (); Q=read (); for(intI=1; i<n;i++) {x=read (); Y=read (); Z=read (); Add (x, y, z); Add (y,x,z); } DFS (1,0); cout<<dp[1][Q];}voidDfsintKintf) {intnum=0;intV for(intI=head[k];i;i=edge[i].next) {v=edge[i].to;if(v==f)Continue; Son[k][num]=v; W[K][NUM]=EDGE[I].V; num++; DFS (V,K); }if(!num)return; for(intI=1; i<=q;i++) { for(intj=0; j<=i;j++) {if(j==0) Dp[k][i]=max (dp[k][i],dp[son[k][1]][i-1]+w[k][1]);Else if(j==i) Dp[k][i]=max (dp[k][i],dp[son[k][0]][i-1]+w[k][0]);ElseDp[k][i]=max (dp[k][i],dp[son[k][0]][j-1]+dp[son[k][1]][i-j-1]+w[k][0]+w[k][1]); } }}
[Luogu2015] Two-prong apple tree (tree-shaped DP)