//树结点的链接可以和图的邻接链表一样,这样也很方便 /* ID:1192432 PROG: castle LANG: C++ */ #include <iostream> #include <queue> #include <stack> #include <string> #include <map> #include <vector> #include <memory.h> #include <cstdio> #include <cmath> #include <algorithm> using namespace std; const int MAX=6005,INF=1<<30; struct Edge{ int v,next; }; int n,l,k,a[MAX]; int len,first[MAX]; Edge e[MAX]; bool vis[MAX]; int root; int f[MAX]; int dp(int u){ if(vis[u]) return f[u]; int sum=0,v,t=0; //choose u sum=a[u]; for(int i=first[u];i!=-1;i=e[i].next){ v=e[i].v; //t is not choose t+=dp(v); for(int j=first[v];j!=-1;j=e[j].next){ sum+=dp(e[j].v); } } f[u]=max(sum,t); vis[u]=1; return f[u]; // //not choose u // for(int i=first[u];i!=-1;i=e[i].next){ // v=e[i].v; // t+=dp(v); // } } int main() { #ifndef ONLINE_JUDGE freopen("i.txt", "r", stdin); #endif while(cin>>n){ len=0; memset(first,-1,sizeof(first)); memset(vis,0,sizeof(vis)); for(int i=1;i<=n;i++) cin>>a[i]; while(cin>>l>>k){ if(l==0&&k==0) break; vis[l]=1; e[len].v=l; e[len].next=first[k]; first[k]=len++; } for(int i=1;i<=n;i++){ if(!vis[i]){ root=i; break; } } memset(vis,0,sizeof(vis)); //cout<<root<<endl; cout<<dp(root)<<endl; } return 0; }