#include using namespace std; #define ll long long #define ull unsigned long long #define ld long double using LL = long long; using ULL = unsigned long long; using VI = vector; using VVI = vector; using VVVI = vector; using VL = vector; using VVL = vector; using VVVL = vector; using VB = vector; using VVB = vector; using VVVB = vector; using VD = vector; using VVD = vector; using VVVD = vector; using VC = vector; using VS = vector; using VVC = vector; using PII = pair; using PLL = pair; using PDD = pair; using PIL = pair; using MII = map; using MLL = map; using SI = set; using SL = set; using MSI = multiset; using MSL = multiset; template using MAXPQ = priority_queue; template using MINPQ = priority_queue< T, vector, greater >; const ll MOD = 1000000007; const ll MOD2 = 998244353; const ll INF = 1LL << 60; #define PI 3.14159265358979323846 #define FOR(i, a, b) for(int i = (a); i < (b); ++i) #define REP(i, n) FOR(i, 0, n) #define EACH(e, v) for(auto &e : v) #define RITR(it, v) for(auto it = (v).rbegin(); it != (v).rend(); ++it) #define ALL(v) v.begin(),v.end() vector x8={1,1,1,0,0,-1,-1,-1},y8={1,0,-1,1,-1,1,0,-1}; int dx4[4]={1,-1,0,0}, dy4[4]={0,0,1,-1}; /* memo -uf,RMQ(segtree),BIT,BIT2,SegTree,SegTreeLazy -isprime,Eratosthenes,gcdlcm,factorize,divisors,modpow,moddiv nCr(+modnCr,inverse,extend_euclid.powmod),tobaseB,tobase10 -dijkstra,Floyd,bellmanford,sccd,topological,treediamiter -compress1,compress2,rotate90 -co,ci,fo1,fo2,fo3,fo4 -bitsearch,binaryserach -bfs -SegTreedec,SegTreeLazydec */ //要素数Nの有向グラフGの頂点に順序をつける template VL topological_sort(const VVL &G, T N){ VL indeg(N, 0); for(ll i = 0; i < N; i++){ for(auto c : G[i]){ indeg[c]++; } } priority_queue> heap; for(ll i = 0; i < N; i++){ if(indeg[i] == 0) heap.push(i); } VL ans; while(!heap.empty()){ int state = heap.top(); heap.pop(); ans.push_back(state); for(auto next : G[state]){ indeg[next]--; if(indeg[next] == 0) heap.push(next); } } return ans; } int main(){ cin.tie(0); ios_base::sync_with_stdio(0); ll N; cin >> N; VL s(N); for(ll i = 0; i < N; i++) cin >> s[i]; VVL G(N); for(ll i = 0; i < N-1; i++){ ll a,b; cin >> a >> b; a--,b--; if(s[a] < s[b]) G[a].push_back(b); if(s[a] > s[b]) G[b].push_back(a); } VL id = topological_sort(G,N); VL dp(N,0); for(ll i = 0; i < N; i++){ ll from = id[i]; for(auto to : G[from]){ dp[to] = max(dp[to],dp[from]+s[from]); } } ll ans = 0; for(ll i = 0; i < N; i++) ans = max(ans,dp[i]+s[i]); cout << ans << '\n'; }