Problem Description
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?
Input
Each test instance first contains two integers, N, M. (1 <= M <= N <= 200); In the next N rows, each row contains two integers, a, B. in line I, a represents that to conquer castle I, you must first conquer Castle a. If a = 0, you can directly conquer castle I. B indicates the number of treasures in castle I, and B> = 0. When N = 0, M = 0, the input ends.
Output
For each test instance, an integer is output, which indicates the maximum number of treasures that ACboy obtains when attacking M castles.
Sample Input
3 2
0 1
0 2
0 3
7 4
2 2
0 1
0 4
2 1
7 1
7 6
2 2
0 0
Sample Output
5
13
The question is not explained much. After all, Chinese questions
I am also referring to other people's code, because this question is combined with the idea of 01 backpack, I did not think of it at first
# Include <stdio. h> # include <string. h ># include <algorithm> using namespace std; struct node {int from, to, next;} tree [205]; int vis [205], dp [205] [205], ans [205] [205], head [205], mat [205]; int len, n, m; void add (int, int B) {tree [len]. from = a; tree [len]. to = B; tree [len]. next = head [a]; head [a] = len ++;} void dfs (int root) {int I, j, k, tem; vis [root] = 1; for (I = head [root]; I! =-1; I = tree [I]. next) {tem = tree [I]. to; if (! Vis [tem]) {dfs (tem); for (k = m; k> = 0; k --) // 01 backpack {for (j = 0; j <= k; j ++) ans [root] [k] = max (ans [root] [k], ans [root] [k-j] + dp [tem] [j]) ;}}for (j = 1; j <= m + 1; j ++) dp [root] [j] = ans [root] [J-1] + mat [root];} int main () {int I, a, B; while (~ Scanf ("% d", & n, & m), n + m) {len = 0; memset (head,-1, sizeof (head )); for (I = 1; I <= n; I ++) {scanf ("% d", & a, & B); mat [I] = B; add (a, I);} mat [0] = 0; memset (vis, 0, sizeof (vis); memset (dp, 0, sizeof (dp )); memset (ans, 0, sizeof (ans); dfs (0); printf ("% d \ n", dp [0] [m + 1]);} return 0 ;}