-----------
const int maxn=10000; const int maxm=110000; int n; struct EdgeNode{ int to,next; }edges[maxm]; int head[maxn],edge; void init(){ memset(head,-1,sizeof(head)); edge=0; } void addedge(int u,int v){ edges[edge].to=v,edges[edge].next=head[u],head[u]=edge++; } int a[maxn]; int f[maxn][2]; int id[maxn]; int dfs(int u,int flag){ if (f[u][flag]!=-1) return f[u][flag]; int res; if (flag){ res=0; for (int i=head[u];i!=-1;i=edges[i].next){ int v=edges[i].to; res+=dfs(v,0); } } else{ int res1=0,res2=0; for (int i=head[u];i!=-1;i=edges[i].next){ int v=edges[i].to; res1+=dfs(v,1); } for (int i=head[u];i!=-1;i=edges[i].next){ int v=edges[i].to; res2+=dfs(v,0); } res=max(res1+a[u],res2); } return f[u][flag]=res; } int main(){ while (~scanf("%d",&n)){ init(); memset(f,-1,sizeof(f)); memset(id,0,sizeof(id)); for (int i=1;i<=n;i++) scanf("%d",&a[i]); int x,y; while (~scanf("%d%d",&x,&y)){ if (x==0&&y==0) break; addedge(y,x); id[x]++; } int rt=1; for (int i=1;i<=n;i++){ if (id[i]==0) rt=i; } printf("%d ",dfs(rt,0)); } return 0; }
-----------