#include namespace { #pragma GCC diagnostic ignored "-Wunused-function" #include #pragma GCC diagnostic warning "-Wunused-function" using namespace std; using namespace atcoder; #define rep(i,n) for(int i = 0; i < (int)(n); i++) #define rrep(i,n) for(int i = (int)(n) - 1; i >= 0; i--) #define all(x) begin(x), end(x) #define rall(x) rbegin(x), rend(x) template bool chmax(T& a, const T& b) { if (a < b) { a = b; return true; } else return false; } template bool chmin(T& a, const T& b) { if (b < a) { a = b; return true; } else return false; } using ll = long long; using P = pair; using VI = vector; using VVI = vector; using VL = vector; using VVL = vector; } int main() { ios::sync_with_stdio(false); cin.tie(0); int n; cin >> n; n++; VI a(n); rep(i, n) cin >> a[i]; VVI to(n); rep(i, n - 1) { int u, v; cin >> u >> v; to[u].emplace_back(v); to[v].emplace_back(u); } vector ord(n); iota(ord.begin(), ord.end(), 0); sort(ord.begin(), ord.end(), [&](int i, int j) { return a[i] < a[j]; }); VI pos(n); rep(i, n) pos[ord[i]] = i; segtree seg(n); fenwick_tree ft(n); VL ans(n); auto dfs = [&](auto&& self, int u, int p, int d) -> void { seg.set(pos[u], 1); ft.add(pos[u], a[u]); if (d >= 2) { int l0 = seg.max_right(0, [&](int x) { return x <= 0; }); int l1 = seg.max_right(0, [&](int x) { return x <= 1; }); int r0 = seg.min_left(n, [&](int x) { return x <= 0; }); int r1 = seg.min_left(n, [&](int x) { return x <= 1; }); if (a[ord[l0]] == a[ord[r0 - 1]]) { ans[u] = 1; } else { ans[u] = 4e18; for (auto [l, r] : {pair(l0, r1), pair(l1, r0)}) { int cnt = d + 1 - 1; int c = seg.max_right(l, [&](int x) { return x <= cnt / 2; }); chmin(ans[u], ft.sum(c, r) - ft.sum(l, c) + (- ((cnt + 1) / 2) + cnt / 2) * a[ord[c]]); } } } else { ans[u] = -1; } for (int v : to[u]) if (v != p) self(self, v, u, d + 1); ft.add(pos[u], -a[u]); seg.set(pos[u], 0); }; dfs(dfs, 0, -1, 0); rep(i, n) if (i) cout << ans[i] << '\n'; }