#include<iostream> #include<algorithm> #define maxn 200010 #define ll long long usingnamespacestd;
int n, m, h[maxn];
structEdge { int to, next; } e[maxn * 2]; int c1, head[maxn]; inlinevoidadd_edge(int u, int v){ e[c1].to = v; e[c1].next = head[u]; head[u] = c1++; }
ll ans; intdfs(int u, int fa){ int mx = 0, sm = 0; for (int i = head[u]; ~i; i = e[i].next) { int v = e[i].to, t; if (v == fa) continue; t = dfs(v, u); if (t > mx) sm = mx, mx = t; elseif (t > sm) sm = t; } if (fa) ans += max(0, h[u] - mx); else ans += h[u] - mx + h[u] - sm; return max(mx, h[u]); }
intmain(){ fill(head, head + maxn, -1); ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);
cin >> n; for (int i = 1; i <= n; ++i) cin >> h[i]; for (int i = 1; i < n; ++i) { int x, y; cin >> x >> y; add_edge(x, y); add_edge(y, x); } int rt = max_element(h + 1, h + n + 1) - h; dfs(rt, 0); cout << ans << "\n"; return0; }