Question:
Give some people 1 to n to join a party. Everyone has their own happiness, but there is a leader relationship between these people.
It is required that everyone cannot participate directly with their own leaders to seek the maximum value to satisfy the requirements.
Solution:
Recursive the building of the leadership relationship from the root node (but I am using an array to save a lot of time space. I can use a two-dimensional dynamic array)
DP [I] [1] indicates the maximum value of the selected I node, and DP [I] [0] indicates the maximum value of the unselected I node.
Then the equation is
DP [I] [1] + = All DP [I children] [0)
DP [I] [0] + = max (all DP [I children] [0], all DP [I children] [1]) (I not selected, then his child can choose or not. We choose the maximum value of the two)
# Include <cstdio> # include <iostream> # include <cstring> # include <algorithm> using namespace STD; int DP [6005] [2]; // DP [I] [1] indicates taking I dp [I] [0] indicates not taking int son [6010] [1000]; // son [I] [J] int root [6010], n, a, B; void DFS (int K) // is this the feeling of searching? {Int J, M, s; M = Son [k] [0]; for (j = 1; j <= m; j ++) // m> 0 subnodes will be in the cycle. m = 0 has reached the bottom {S = Son [k] [J]; DFS (s ); DP [k] [1] + = DP [s] [0]; // when K is used, the subnode cannot obtain DP [k] [0] + = max (DP [s] [0], DP [s] [1]); // if K is not used, the subnode can fetch the largest value} int main () {int I, K; while (~ Scanf ("% d", & N) {memset (root, 0, sizeof (Root); memset (son, 0, sizeof (son); memset (DP, 0, sizeof (DP); for (I = 1; I <= N; I ++) scanf ("% d", & DP [I] [1]); while (scanf ("% d", & A, & B) & (A | B )) {son [B] [++ son [B] [0] =; // copy the user's son [B] [0] saves the number of B's sons, saving the code. Root [a] = 1; // locate the root node} for (I = 1; I <= N; I ++) // locate the root node K if (! Root [I]) {k = I; break;} DFS (k); printf ("% d \ n", max (DP [k] [0], DP [k] [1]);} return 0 ;}