You can build a tree based on the meaning of the question.
To take over child nodes, you must first take over Father's Day points and establish a forest based on this relationship.
The forest becomes a tree by referencing a tree related to all the roots from node 0.
Status definition
OPT [I] [J] indicates the maximum value obtained by selecting J points in the subtree with node I as the root.
Status Transfer
Gem [I] is the input B
OPT [I] [J] = OPT [son1] [J1] + OPT [son2] [J2] + .... + OPT [son-M] [JM] + GEM [I]
D [II] indicates the maximum value obtained by selecting the second node in all the subtree of node I. The array D is calculated using the grouping backpack.
Then OPT [I] [J] = d [J-1] + GEM [I]
Therefore, for OPT [I] [0... m], you can calculate the array D obtained by a grouping backpack.
CodeAs follows:
# include
# include
# include
# include
using namespace STD; int N, m; bool flag [220]; int gem [220]; // gem [I] indicates the number of treasures in castle I. Vector
A [220]; // tree storage. The valid number of the castle is 1, 2, and N. Add a non-existent Castle 0 as the root int OPT [220] [220]. // OPT [I] [J] indicates the maximum value of void DFS (int r) obtained by J nodes in the subtree where I is the root. // In the subtree where R is the root, calculate OPT [r] [0 .... m] {flag [R] = true; For (INT I = 0; I
= 0; j --) {for (int K = 0; k <= J; k ++) {d [J] = max (d [J], d [J-K] + OPT [A [r] [I] [k]) ;}} OPT [r] [0] = 0; for (INT I = 1; I <= m; I ++) {OPT [r] [I] = d [I-1] + GEM [R];} int main () {While (scanf ("% d", & N, & M), N | M) {memset (flag, false, sizeof (FLAG); For (INT I = 0; I <= N; I ++) {A [I]. clear () ;}for (INT I = 1; I <= N; I ++) {int A; scanf ("% d", &, & gem [I]); A [A]. push_back (I);} gem [0] = 0; // build M ++; DFS (0); printf ("% d \ n ", OPT [0] [m]);} return 0 ;}