```cpp
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=6005;
const int inf=0x3f3f3fll;
typedef long long ll;
#define max(a,b) a<b?b:a
#define maxx(a,b,c) max(max(a,b),c)
#define maxxx(a,b,c,d) max(max(max(a,b),c),d)
inline char getc()
{
static char buf[1<<14],*p1=buf,*p2=buf;
return (p1==p2)&&(p2=(p1=buf)+fread(buf,1,1<<14,stdin),p1==p2)?EOF:*p1++;
}
inline int read()
{
int data=0,w=1;
char ch=0;
while(ch!='-'&&(ch<'0'||ch>'9'))ch=getc();
if(ch=='-') w=-1,ch=getc();
while(ch>='0'&&ch<='9') data=data*10+ch-'0',ch=getc();
return data*w;
}
int n,x,y,root,head[maxn<<1],next[maxn<<1],deg[maxn<<1],p=0,f[3][maxn];
inline void add(int u,int v)
{
next[v]=head[u];
head[u]=v;
return;
}
inline void dfs(int u)
{
for(register int i=head[u];i;i=next[i])
{
dfs(i);
f[1][u]=maxx(f[1][u],f[0][i],f[0][i]+f[1][u]);
f[0][u]=maxxx(f[0][u],f[0][i],f[0][u]+f[0][i],f[0][u]+f[1][i]);
}
return;
}
int main()
{
n=read();
for(register int i=1;i<=n;i++)
f[1][i]=read();
for(register int i=1;i<=n;i++)
{
x=read(),y=read();
deg[x]++;
if(i==n) continue;
add(y,x);
}
for(register int i=1;i<n;i++)
{
if(!deg[i])
{
root=i;
break;
}
}
dfs(root);
printf("%d",max(f[0][root],f[1][root]));
return 0;
}
```
by Explorer_CYC @ 2018-04-26 20:04:21