Test instructions: Give you a tree, each node in the tree has a weight, father and son can not be selected at the same time, the maximum weight value
Dp[u][0] represents the maximum weight when the U node is not selected, and Dp[u][1] represents the maximum weight when you select U.
Dp[u][1]+=dp[v][0], when choosing a father, add the choice of a son.
Dp[u][0]=max (dp[v][0],dp[v][1]), do not choose a father, can choose son, also can not choose, take the biggest.
Keep track of which point there is no father, then you can use that point to run DFS at once.
#include <iostream>#include<cstdio>#include<cstring>#include<ctime>#include<algorithm>#include<cstdlib>#include<cmath>#include<map>#include<Set>using namespaceStd;typedefLong Longll;typedef unsignedLong LongUll;typedefDoubledb;#defineX First#defineY Second#defineMP (A, b) Make_pair (A, B)#definePB Push_back#defineSD (x) scanf ("%d",& (x))#definePi ACOs (-1.0)#defineSF (x) scanf ("%lf",& (x))#defineSS (x) scanf ("%s", (x))#defineMAXN 50005Const intinf=0x3f3f3f3f;Constll mod=1000000007;#defineN 6005intdp[n][2],vis[n],po[n];intE,n;intHead[n];structnode{intV,next;} Edge[n];voidAddedge (intUintv) {EDGE[E].V=v; Edge[e].next=Head[u]; Head[u]=e++;}voidinit () {memset (head,-1,sizeofhead); memset (Vis,0,sizeofvis); Memset (DP,0,sizeofDP); E=0; for(intI=1; i<=n;i++) SD (Po[i]); intu,v; while(SCANF ("%d%d", &u,&v), u+v) {Addedge (v,u); Vis[u]=1; }}voidDfsintu) {dp[u][0]=0; dp[u][1]=Po[u]; for(inti=head[u];i!=-1; i=Edge[i].next) { intv=edge[i].v; DFS (v); dp[u][1]+=dp[v][0]; dp[u][0]+=max (dp[v][0],dp[v][1]); }}voidWork () {intA; for(a=1; a<=n;a++) if(!vis[a]) Break; DFS (a); cout<<max (dp[a][0],dp[a][1]) <<Endl;}intMain () {#ifdef local freopen ("inch","R", stdin); //freopen ("Out", "w", stdout); int_time=clock ();#endif while(cin>>N) {init (); Work (); } #ifdef local printf ("Time :%d\n",int(Clock ()-_time));#endif}
View Code
HDU 1520 Anniversary Party