Topic PortalThe following:
The first tree knapsack problem Qaq
Consider the type of each node in the final answer: 1, without passing, 2, passing but not returning, 3, passing and returning (the definition returned is that the final stop node is not in the subtree of that node)
For the first type of node, do not consider.
For the latter two types, we set f[i][j][0] to indicate the maximum weight that can be obtained by walking J in the subtree of the I-node and finally returning to the I-node, f[i][j][1] represents the maximum weight that is ultimately not returned to the I node.
For each child node of a node, select one of these states. We can put the problem abstract ingredient group knapsack problem: a backpack with a capacity of J, there are siz group items (siz equivalent to the number of child nodes), each group of items can only choose one. Then we can get the state transition equation:
F[i][j][0] = max{f[v][k][0]+f[i][j-k-2][0]} (since you want to go back to the node, then for the sub-node V must also go back to the V-node, and go up each step, so use two more steps)
F[I][J][1] = max{f[v][k][0]+f[i][j-k-2][1]} (for the V-node, it will not come back, then the other nodes must come back)
F[I][J][1] = max{f[v][k][1]+f[i][j-k-1][0]} (the node returns, then other nodes can not be returned)
1#include <iostream>2#include <cstdio>3#include <cstring>4 #defineLL Long Long5 #defineRI Register int6 using namespacestd;7 Const intINF =0x7ffffff ;8 Const intN = -+Ten ;9 Const intK = $+Ten ;Ten OneInlineintRead () { A intK =0, F =1;Charc =GetChar (); - for(;!isdigit (c); C =GetChar ()) - if(c = ='-') F =-1 ; the for(; IsDigit (c); C =GetChar ()) -K = k*Ten+ C'0' ; - returnk*F; - } + - structEdge { + intto, next; A}e[n<<1] ; at intN, k, cnt =0;intHead[n], W[n], f[n][k][2] ;//0 means back, 1 means not coming back. -InlinevoidAdd_edge (intXinty) { -e[++cnt].to = y, E[cnt].next = head[x], head[x] =CNT; - } - - voidDfsintXintFA) { in for(intj=0; j<=k;j++) f[x][j][0] = f[x][j][1] =W[x]; - for(intI=head[x];i;i=E[i].next) { to inty = e[i].to;if(y = = FA)Continue ; + DFS (y,x); - for(intj=k;j>=0; j--) { the for(intkk=0; kk<=j;kk++) { * if(J >= kk+2) f[x][j][0] = max (f[x][j][0],f[x][j-kk-2][0]+f[y][kk][0]) ; $ if(J >= kk+2) f[x][j][1] = max (f[x][j][1],f[x][j-kk-2][1]+f[y][kk][0]) ;Panax Notoginseng if(J >= kk+1) f[x][j][1] = max (f[x][j][1],f[x][j-kk-1][0]+f[y][kk][1]) ; - } the } + } A } the + intMain () { - while(~SCANF ("%d%d",&n,&k)) { $CNT =0; Memset (Head,0,sizeof(head)); $ for(intI=1; i<=n;i++) W[i] =read (); - for(intI=1; i<n;i++) { - intx = Read (), y =read (); the Add_edge (x, y); Add_edge (y,x); - }WuyiDfs1,0) ; theprintf"%d\n", Max (f[1][k][0],f[1][k][1])) ; - } Wu return 0 ; -}
The first time it was wrong. Only one of the children can go down and not come back Qwq
Apple Tree (POJ2486