Exercises
Independent set of tree problems ...
The independent set problem of tree has two kinds of writing on DP, one is search, one is brush table.
This is a brush table.
Test instructions: Given a tree, the root node is 1, which requires the selection of the most nodes according to the following requirements:
① cannot choose 1
② If the current node is selected, neither the parent nor the son of the node can be selected.
③ If a node's son node is selected, the other sons of that node cannot be selected. (Chinese test Instructions link: http://blog.csdn.net/qian99/article/details/16970341)
The key is for the 3rd case.
Dp[u][0] Indicates the current point is not selected, Dp[u][1] indicates the current point selection
Divided into 2 kinds of the first is that all sons do not choose, the second choice of an optimal son, then the equivalent of the first all do not choose the son. Then be sure to choose the son, choose Dp[v][1]-dp[v][0] The biggest on the line. Specific look at the code
Code:
#include <iostream>#include<cstring>#include<algorithm>#include<cmath>#include<cstdio>using namespacestd;#definePB Push_back#defineMP Make_pair#defineSe Second#defineFS First#defineLL Long Long#defineCLR (x) memset (x,0,sizeof x)#defineMC (x, y) memcpy (x,y,sizeof (×))#defineSZ (x) ((int) (x). Size ())#definefor (It,c) for (__typeof ((c). Begin ()) it= (c). Begin (); it!= (c). end (); it++)#defineLson l,m,rt<<1#defineRson m+1,r,rt<<1|1typedef pair<int,int>P;Const Doubleeps=1e-9;Const intn=5e5+Ten;Const intm=1e3+Ten;ConstLL mod=1000000007;Const intinf=1e9+Ten;intN,cnt,num;inthead[n],dp[n][2],ans[n],to[n];structedge{intV,NXT;} Edge[n*2];voidInit () {CNT=0; Num=0; memset (Head,-1,sizeof(head));}voidAddedge (intUintv) {EDGE[CNT].V=v; EDGE[CNT].NXT=Head[u]; Head[u]=cnt++;}voidDfsintu) {dp[u][0]=0, dp[u][1]= +; inttmp=-INF; for(inti=head[u];i!=-1; i=edge[i].nxt) { intv=edge[i].v; DFS (v); dp[u][1]+=dp[v][0]; dp[u][0]+=dp[v][0]; if(dp[v][1]-dp[v][0]>tmp) {tmp=dp[v][1]-dp[v][0]; To[u]=v; } } if(tmp>0) dp[u][0]+=tmp; Elseto[u]=0;}voidFind_path (intUintk) { intbest=-1; if(k==0) best=To[u]; if(k==1) ans[num++]=u; for(inti=head[u];i!=-1; i=edge[i].nxt) { intv=edge[i].v; if(k==1) Find_path (V,0); if(k==0){ if(v==best) Find_path (V,1); ElseFind_path (V,0); } }}intMain () {Init (); scanf ("%d",&N); for(intI=2; i<=n;i++){ intx; scanf ("%d",&x); Addedge (X,i); } DFS (1); printf ("%d\n", dp[1][0]); Find_path (1,0); Sort (Ans,ans+num); for(intI=0; i<num;i++) printf ("%d%c", Ans[i], (i==num-1?'\ n':' ')); return 0;}
SGU195 New Year Bonus Grant