Link: hdu-1561
Question
ACboy is very fond of playing a strategic game. on a map, there are N castles, each of which has certain treasures, in each game, ACboy allows him to conquer M castles and gain the treasures in them. However, due to the geographical location, some castles cannot be directly conquered. To conquer these castles, you must first conquer another particular Castle. Can you help ACboy figure out which M castle should be conquered to obtain as many treasures as possible?
Ideas
Simple tree-shaped backpack dp, as the first entry to the tree-shaped backpack is very suitable
If the question is about the forest, add a "Root Node" to point to the root node of each tree in the forest.
F (I, j) indicates subtree I, which is the maximum value when j Castle treasures are used.
The child Tree represented by each subnode of I can be seen as a group of items, in this child tree can choose to take 1, 2, 3... J-1 castle treasure
This is equivalent to grouping A backpack for each subnode.
F (I, j) = max {f (I, j-k) + f (v, k) | 1 <= k <j} | v is the subtree of I}
Because a root node is added and the parent node must be taken before the child node is taken, the m value must be increased by 1 to take the root node.
There is an optimization. For a subtree, the number of nodes in the subtree cannot exceed the number of nodes in the subtree. The optimization can reach 0 MS.
Code
/** =================================================== =================== * This is a solution for ACM/ICPC problem ** @ source: hdu-1561 The more, The Better * @ description: Tree backpack dp * @ author: shuangde * @ blog: blog.csdn.net/shuangde800 * @ email: zengshuangde@gmail.com * Copyright (C) 2013/08/20 All rights reserved. * ===================================================== ===================*/# include <iostream> # include <cst Dio> # include <algorithm> # include <vector> # include <queue> # include <cmath> # include <cstring> # define MP make_pairusing namespace std; typedef pair <int, int> PII; typedef long int64; const int INF = 0x3f3f3f; const double PI = acos (-1.0); const int MAXN = 210; vector <int> adj [MAXN]; int val [MAXN]; int tot [MAXN]; int f [MAXN] [MAXN]; int n, m; int dfs (int u) {f [u] [1] = val [u]; tot [u] = 1; for (int I = 0; I <Adj [u]. size (); ++ I) {int v = adj [u] [I]; tot [u] + = dfs (v) ;}for (int I = 0; I <adj [u]. size (); ++ I) {int v = adj [u] [I]; for (int s = tot [u]> m? M: tot [u]; s> = 1; -- s) {for (int j = 1; j <s & j <= tot [v]; ++ j) {f [u] [s] = max (f [u] [s], f [u] [s-j] + f [v] [j]) ;}}return tot [u] ;}int main () {while (~ Scanf ("% d", & n, & m) & n + m) {// init for (int I = 0; I <= n; ++ I) adj [I]. clear (); val [0] = 0; for (int I = 1; I <= n; ++ I) {int a; scanf ("% d ", & a, & val [I]); if (a) {adj [a]. push_back (I);} else {adj [0]. push_back (I) ;}} memset (f, 0, sizeof (f); ++ m; dfs (0); printf ("% d \ n ", f [0] [m]);} return 0 ;}