To a tree with a node right, find a subtree with K nodes, and seek the maximum weight of this subtree.
Dp[u][k] represents the maximum weight of a subtree with a U-node that has a size of k in the root of U, and
Then make a group backpack for each child node of U, because for each son of U, you can choose to assign
1,2,3...k-1 a node to it
State transition equation:
When the node size is k, it can be by the root node is U, the subtree size is k-t, plus the root node is V, the subtree size is T the state transfer (V is a child of u), that is:
Dp[u][k] = max (Dp[u][k], dp[u][k-t]+dp[v][t]);//v is the son of U node
#include <iostream>#include<cstdio>#include<cstring>#include<algorithm>#include<vector>using namespacestd;//simple tree-shaped DPintMaxintAintb) { returnA>b?a:b;}Const intINF =1<< -;intn,k;intx[202];intdp[202][202];vector<int> list[202];voidDfsintUintfather) { inti,j; for(i=0; I<list[u].size (); i++) { intv=List[u][i]; if(v==father)Continue; DFS (V,U); for(j=k;j>=1; j--)//must be reversed . { for(intt=1; t<=j;t++) Dp[u][j]=max (Dp[u][j], dp[u][t]+dp[v][j-T]); } }}intMain () {scanf ("%d%d",&n,&k); inti,j,a,b; for(i =0; I <= n;i++)//Empty List Tablelist[i].clear (); Memset (DP,0,sizeof(DP)); dp[0][1]=0;//maximum weight with 0 nodes and only 1 words in the root node for(i=1; i<=n;i++) {scanf ("%d%d", &b,&dp[i][1]);//maximum weight with I as the root node with only 1 words in the nodeList[i].push_back (b); List[b].push_back (i); } k++;//Add a 0 nodeDfs0,-1); printf ("%d\n", dp[0][k]);//maximum weight with 0 for the root node and only the number of words in M nodes return 0;}
Tree-shaped DP