Reprint please indicate the source, thank you: http://www.cnblogs.com/KirisameMarisa/p/4316097.html---by ink dyeing sakura
"Topic link" http://poj.org/problem?id=2342
"Title description" an enterprise has n employees, and everyone has a value that indicates the degree of happiness. Now a party, but these employees have a subordinate relationship, each employee does not want to see their direct boss, that is, every employee can not and direct boss at the same time. The maximum value of the total joy of the party at the scene
The "idea" of the most basic tree-shaped DP, is now based on the hierarchy of the tree-like forest, and then on each tree dynamic planning, dp[i][0] and dp[i][1] that I is the root of the subtree respectively in I do not come and the case of the maximum total joy. There is obviously Dp[i][1]=sum (Dp[j][0]) +a[i],dp[i][0]=sum (max (dp[j][0],dp[j][1)), where J traverses all the son nodes of I. Finally, only the sum of Max (dp[r][0],dp[r][1]) is required for all root nodes in the forest.
#include <iostream>#include<ios>#include<iomanip>#include<functional>#include<algorithm>#include<vector>#include<sstream>#include<list>#include<queue>#include<deque>#include<stack>#include<string>#include<Set>#include<map>#include<cstdio>#include<cstdlib>#include<cctype>#include<cmath>#include<cstring>#include<climits>using namespacestd;#defineXinf Int_max#defineINF 1<<30#defineMAXN 6000+10#defineEPS 1e-10#defineZero (a) fabs (a) <eps#defineSqr (a) ((a) * (a))#defineMP (x, y) make_pair (x, y)#definePB (x) push_back (x)#definePF (x) push_front (x)#defineREP (x,n) for (int x=0; x<n; X + +)#defineREP2 (X,L,R) for (int x=l; x<=r; X + +)#defineDEP (x,r,l) for (int x=r; x>=l; x--)#defineCLR (a,x) memset (a,x,sizeof (A))#defineIT iterator#definePI ACOs (-1.0)#defineTest puts ("OK");#define_ Ios_base::sync_with_stdio (0); Cin.tie (0);typedefLong LongLl;typedef pair<int,int>pii;typedef priority_queue<int,vector<int>,greater<int> >pqi;typedef Vector<PII>vii;typedef Vector<int>VI;#defineX First#defineY SecondVI G[MAXN];intNUM[MAXN];intPAR[MAXN];intdp[maxn][2];intN;voidDfsintR) { if(g[r].size () = =0) {dp[r][0]=0; dp[r][1]=Num[r]; } REP (I,g[r].size ()) DFS (G[r][i]); dp[r][0]=dp[r][1]=0; REP (I,g[r].size ()) dp[r][1]+=dp[g[r][i]][0]; dp[r][1]+=Num[r]; REP (I,g[r].size ()) dp[r][0]+=max (dp[g[r][i]][0],dp[g[r][i]][1]);}intMain () {_ CLR (par,-1); scanf ("%d",&N); REP (i,n) scanf ("%d",&Num[i]); intx, y; while(SCANF ("%d%d",&x,&y)) {if(x==0&& y==0) Break; X--;y--; PAR[X]=y; G[y]. PB (x); } inttot=0; REP (i,n)if(par[i]==-1) {DFS (i); Tot+=max (dp[i][0],dp[i][1]); } printf ("%d\n", tot); return 0;}
View Code
poj2342 Anniversary Party "tree-shaped DP"