#include<bits/stdc++.h>
using namespace std;
#define ft first
#define sd second
typedef long long ll;
typedef vector<bool> veb;
typedef vector<ll> vel;
typedef vector<vel> vevel;
typedef vector<vevel> vevevel;
typedef vector<pair<ll,ll>> velp;
typedef vector<pair<bool,bool>> velb;
typedef vector<char> vec;
typedef map<ll,ll> mll;
typedef map<char,ll> mcl;
typedef map<ll,char> mlc;
typedef map<ll,bool> mlb;
typedef map<char,char> mcc;
typedef vector<pair<char,char>> vecp;
typedef priority_queue<ll> pql;
const ll mo = 1e9+7;
vel v;
vevel shu;
vel value;
int n;
ll initialize(ll x){
value[x]=v[x];
for(auto i:shu[x]){
value[x]+= initialize(i);
}
return value[x];
}
bool bl;
ll ditui(ll x){
ll sum1=0,sum=0;
for(auto i:shu[x]){
ll a=ditui(i);
if(bl){
sum+=a;
sum1+=value[i]-a;
}else{
sum+=value[i]-a;
sum1+=a;
}
bl=false;
}
if(v[x]>0){
sum1+=v[x];
if(sum1>sum){
bl=true;
return sum1;
}else{
bl= false;
return sum;
}
}
bl= false;
return max(sum,sum1);
}
void slv(){
cin>>n;
v=value=vel(n+1);
for(int i=1;i<=n;i++){
cin>>v[i];
}
shu=vevel(n+1);
veb b(n+1);
for(int i=1;i<n;i++){
int l,k;
cin>>l>>k;
shu[k].push_back(l);
b[l]=true;
}
ll x;
for(int i=1;i<=n;i++){
if(!b[i]){
x=i;
break;
}
}
initialize(x);
cout<<ditui(x)<<"\n";
}
int main(){
ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
ll t=1;
while(t--){
slv();
}
return 0;
}