Test Instructions /Description :
There is an apple tree, if the branch has a fork, it must be divided into 2 forks (that is, there is no node of 1 sons)
This 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. Below is a tree with 4 branches
2 5 BR style= "font-size:14px" > \/
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.
Read in / Input :
line 1th 2 numbers, N and Q. n Indicates the number of points in the tree enumeration. Q indicates the number of branches that should be retained.
Down the N-1 line contains a description of the branch. Each description consists of three integers separated by a space. The first two of them are defined by its end point branch. The third number defines the number of apples on this branch. You can assume that no branch contains more than 30000 apples.
Output / Output :
A number, the maximum number of apples that can be retained.
Solving / Solution :
This topic is about two forks, it is easy to think of the tree-type DP. Do not talk nonsense, enter the topic.
If there is only one capacity, take the left and right sides maximum value.
F[t,x]:=max (G[t,l[t]],g[t,r[t]);
If it is larger than one capacity, the first and the left and right sides are assigned.
F[t,x]:=max (F[t,x],f[l[t],i]+f[r[t],x-2-i]);
Then just take the left or just the right.
F[t,x]:=max (f[t,x],f[l[t],x-1]+g[t,l[t]); or F[t,x]:=max (f[t,x],f[r[t],x-1]+g[t,r[t]);
code / code :
<strong>var N,q,o:longint; A,g,f:array [0..101,0..101] of Longint; V:array [0..101] of Boolean; L,r,du:array [0..101] of Longint;function Max (t,k:longint): Longint;begin if T>k then exit (t); Exit (k); End;procedure tree (X:longint); var i:longint;begin if X=0 then exit; V[x]:=true; For I:=1 to a[x,0] does if not v[a[x,i] and then if L[x]=0 then L[x]:=a[x,i] else r[x]:=a[x,i]; Tree (L[x]); Tree (R[x]); end;procedure main (T,x:longint); var i:longint;begin if (x=0) or (t=0) then begin f[t,x]:=0; Exit End If F[t,x]>0 then exit; If X=1 then BEGIN F[t,x]:=max (G[t,l[t]],g[t,r[t]); Exit End For i:=0 to X-2 do begin main (l[t],i); Main (r[t],x-2-i); F[t,x]:=max (F[t,x],f[l[t],i]+f[r[t],x-2-i]); End F[t,x]:=f[t,x]+g[t,l[t]]+g[t,r[t]]; Main (L[T],X-1); F[t,x]:=max (F[t,x],f[l[t],x-1]+g[t,l[t]); Main (R[T],X-1); F[t,x]:=max (F[t,x],f[r[t],x-1]+g[t,r[t]); End;procedure Init;var I,x,y,z:longint;begin reADLN (N,Q); For i:=1 to N-1 do begin READLN (x, y, z); G[x,y]:=z; G[y,x]:=z; Inc (a[x,0]); A[x,a[x,0]]:=y; Inc (a[y,0]); A[y,a[y,0]]:=x; End O:=1; For I:=1 to N does if a[i,0]=2 then begin o:=i; Break End;end;begin Init; Tree (o); Main (O,Q); Write (F[o,q]);end.</strong>
Two-prong apple tree