Test instructions: A university prepares to host the 80 anniversary celebration event. The school's personnel relationship is a tree-shaped structure, the parent node is the boss, sub-node is subordinate. Each node has a value, and the restriction is that the parent node cannot participate in the celebration at the same time (that is, if the parent node participates then his child's node will not be able to participate, if there is a child node to participate, then the Father node can not participate). The maximum value of the value, in the case of the last request to satisfy the limit.
F[n]: Represents the parent node of the I node;
Rating[n]: Value of a node
DP[I][0]: Maximum value of subtree taken with I as root node (I node not taken)
DP[I][1]: Maximum value of subtree taken with I as root node (I node is taken)
State transition equation:
Dp[root][0] + = max (dp[children[root][i]][0], dp[children[root][i]][1]);DP [root][1] + = dp[children[root][i]][0 ];
The final result is one of the maximum value that contains the root node and the maximum value that does not contain the root node.
#include <vector>#include<cstdio>using namespacestd;Const intN =6005;intF[n];intRatings[n];vector<int>Children[n];intdp[n][2];intMaxintAintb) { returna > B?a:b;}voidDfsintroot) { intLen =children[root].size (); dp[root][1] =Ratings[root]; for(inti =0; i < Len; ++i) {DFS (children[root][i]); } for(inti =0; i < Len; ++i) {dp[root][0] + = max (dp[children[root][i]][0], dp[children[root][i]][1]); dp[root][1] + = dp[children[root][i]][0]; }}intMain () {intN, a, B; while(SCANF ("%d", &n)! =EOF) {memset (DP,0,sizeof(DP)); for(inti =1; I <= N; ++i) {scanf ("%d", &Ratings[i]); F[i]= -1; } while(SCANF ("%d%d", &a, &b)) { if(A = =0&& b = =0) Break; F[a]=b; Children[b].push_back (a); } intRoot =1; while(F[root]! =-1) root =F[root]; DFS (root); printf ("%d\n", Max (dp[root][0], dp[root][1])); } return 0;}
Tree-shaped DP--HDU 1520 Anniversary party