This is my first backpack on the tree-shaped structure problem, not very understanding of this concept can first look at the backpack nine talk
Oneself for the first time to do, look at the other people's ideas, combined with the simple knapsack problem solving method of their own once AC or a little excited
The main topic is:
Conquer m cities, each city has a corresponding number of treasures, to conquer a city must ensure that its corresponding to a particular city has been conquered, hoping to get the largest number of treasures
It is easy to draw a tree structure of the corresponding relationship according to the topic, each node has a corresponding number of treasures
We use DP[I][J] to deposit I node under the tree below it has a J city is conquered when the greatest number of treasures, at this time I is not conquered!
Then update from bottom up with Dfs
1 /*2 the total U bottom subtree overcomes j cities, assigning K cities to the current V-Pose3 Add the current v contains the city to conquer the K-1 subtree, to add subtree v must be4 also ensure V is conquered, so add is dp[v][k-1] + val[v]5 */6 for(intj = m; j>=1; j--){7 for(intK = J; K>0; k--){8DP[U][J] = max (Dp[u][j], dp[u][j-k] + dp[v][k-1] +val[v]);9 }Ten}
It can be understood here that if there are J cities under the root node u are conquered, if there are k cities to conquer from the subtree of V, then v must be conquered, Val[v], or the city beneath it cannot conquer
Remove V and k-1 v-node corresponding subtree of the city to conquer, that is dp[v][k-1]
1#include <cstdio>2#include <cstring>3#include <iostream>4 using namespacestd;5 Const intN =205;6 7 intDp[n][n], val[n], first[n], K;8 9 structedge{Ten inty, Next; One }e[n]; A - voidAdd_edge (intXinty) - { theE[k].y = y, E[k].next =First[x]; -FIRST[X] = k++; - } - + voidDfsintU,intm) - { + for(intI=first[u]; i!=-1; I=E[i].next) { A intv =e[i].y; at Dfs (v, m); - /* - the total U bottom subtree overcomes j cities, assigning K cities to the current V-Pose - Add the current v contains the city to conquer the K-1 subtree, to add subtree v must be - also ensure V is conquered, so add is dp[v][k-1] + val[v] - */ in for(intj = m; j>=1; j--){ - for(intK = J; K>0; k--){ toDP[U][J] = max (Dp[u][j], dp[u][j-k] + dp[v][k-1] +val[v]); + } - } the } * } $ Panax Notoginseng intMain () - { the //freopen ("a.in", "R", stdin); + intN, M, A, b; A while(SCANF ("%d%d", &n, &m), n| |m) the { +memset (First,-1,sizeof(first)); -K =0; $ for(intI=1; I<=n; i++) $ { -scanf"%d%d", &a, &b); - Add_edge (A, i); theVal[i] =b; - }WuyiMemset (DP,0,sizeof(DP)); theDfs0, m); - Wuprintf"%d\n", dp[0][m]); - } About return 0; $}
HDU 1561 tree-shaped DP backpack problem