Now, similar to array problem, we have to make a decision about including node V in our subset or not. If we include node V, we can’t include any of its children(say _v_1, _v_2, …, v__n), but we can include any grand child of V. If we don’t include V, we can include any child of V.
So, we can write a recursion by defining maximum of two cases..
As we see in most DP problems, multiple formulations can give us optimal answer. Here, from an implementation point of view, we can define an easier solution using DP. We define two DPs,and, denoting maximum coins possible by choosing nodes from subtree of node V and if we include node V in our answer or not, respectively. Our final answer is maximum of two case i.e..
And defining recursion is even easier in this case.(since we cannot include any of the children) and(since we can include children now, but we can also choose not include them in subset, hence max of both cases).
1/* ***********************************************
2Author :111qqz
3Created Time :2016年11月30日 星期三 20时37分22秒
4File Name :code/hdu/1520.cpp
5************************************************ */ 6#include<cstdio> 7#include<cstring> 8#include<iostream> 9#include<algorithm>10#include<vector>11#include<queue>12#include<set>13#include<map>14#include<string>15#include<cmath>16#include<cstdlib>17#include<ctime>18#define fst first
19#define sec second
20#define lson l,m,rt<<1
21#define rson m+1,r,rt<<1|1
22#define ms(a,x) memset(a,x,sizeof(a))
23typedeflonglongLL;24#define pi pair < int ,int >
25#define MP make_pair
26usingnamespacestd;27constdoubleeps=1E-8;28constintdx4[4]={1,0,0,-1};29constintdy4[4]={0,-1,1,0};30constintinf=0x3f3f3f3f;31constintN=6E3+7;32inta[N];33intn;34intdp1[N],dp2[N];35vector<int>edge[N];36intin[N];37introot;38voiddfs(intu,intpre)39{40intsum1=0,sum2=0;41for(autov:edge[u])42{43if(v==pre)continue;44dfs(v,u);45sum1+=dp2[v];46sum2+=max(dp1[v],dp2[v]);47}48dp1[u]=a[u]+sum1;49dp2[u]=sum2;50}51intmain()52{53#ifndef ONLINE_JUDGE
54freopen("code/in.txt","r",stdin);55#endif
56while(~scanf("%d",&n))57{58ms(in,0);59ms(dp1,0);60ms(dp2,0);61for(inti=1;i<=n;i++)edge[i].clear();62for(inti=1;i<=n;i++)scanf("%d",&a[i]);63intu,v;64while(~scanf("%d%d",&u,&v))65{66if(u==0&&v==0)break;67edge[u].push_back(v);68edge[v].push_back(u);69in[u]++;70}71for(inti=1;i<=n;i++)72if(in[i]==0)73{74root=i;75break;76}77dfs(root,-1);78intans=max(dp1[root],dp2[root]);79printf("%d\n",ans);80}81#ifndef ONLINE_JUDGE
82fclose(stdin);83#endif
84return0;85}