Main topic:
Employees to participate in the annual party, if not meet the direct boss, then the staff will have a happy value, we want to make employees ' happy value maximum
First enter N, then the 1~n number of the employee's corresponding happy value
Then continue to enter the leadership relationship between employees, L,k said K is the boss of L, until the end of the output 0,0
This is the first time to contact the topic of tree-type DP, it seems to be the most recommended topic, DP's idea is from other great God place,
According to the idea of tree DP, I wrote it again, it is easy to see that the parent node is always affected only by the child nodes.
So we always update from the leaf to the root of the tree, through Dfs constantly access to the leaf node, and then recursively back, until the root to obtain the overall optimal solution
There are n people here, everyone has come or not, so we define a
DP[N][2] indicates that both states
Dp[i][0] means I this employee does not come when the corresponding I this subtrees tree obtained the optimal solution
Dp[i][1] represents the optimal solution for I, the subtrees tree, that the employee comes from.
Dp[u][0] + = Max{dp[v][0], dp[v][1]} v->u
DP[U][1] + = max{dp[v][0]} v->u (v is the child node of U)
DP[U][1] to give the initial value val[u] (happy value of u number)
1#include <iostream>2#include <cstdio>3#include <cstring>4 5 using namespacestd;6 Const intN =6010;7 intVal[n], dp[n][2], Flag[n], first[n], K;8 9 structedge{Ten inty, Next; One}e[n*n/2]; A - voidAdd_edge (intXinty) - { theE[k].y = y, E[k].next =First[x]; -FIRST[X] = k++; - } - + voidDfsintu) - { +dp[u][1] =Val[u]; A for(intI=first[u]; i!=-1; I=E[i].next) { at intv =e[i].y; - Dfs (v); -dp[u][0] + = max (dp[v][0], dp[v][1]); -dp[u][1] + = dp[v][0]; - } - } in - intMain () to { + //freopen ("a.in", "R", stdin); - intN, a, B; the while(SCANF ("%d", &n) = =1) * { $ for(intI=1; I<=n; i++)Panax Notoginsengscanf"%d", val+i); - thememset (Flag,0,sizeof(flag));//to find the roots . +memset (First,-1,sizeof(first)); A while(SCANF ("%d%d", &a, &b), a&&b) { the Add_edge (b, a); +Flag[a] =1; - } $ $ intRoot; - /* - do not know whether there is only one root node, also need to consider, the but seemingly direct, it seems that the topic is to ensure that there is only one - the highest boss, the only rootWuyi */ the for(inti =1; I<=n; i++) - if(!flag[i]) root=i; Wu -Memset (DP,0,sizeof(DP)); About Dfs (root); $ /*for (int i = 1; i<=n; i++) { - cout<< "I:" <<i<< "<<dp[i][0]<< " "<<dp[i][1]<<endl; - }*/ -printf"%d\n", Max (dp[root][0], dp[root][1])); A } + return 0; the}
HDU 1520 Anniversary Party tree DP