from collections import deque N = int(input()) A = [int(a) for a in input().split()] E = [[] for _ in range(N)] for _ in range(N - 1): a, b = map(int, input().split()) E[a-1].append(b-1) E[b-1].append(a-1) X = [[] for i in range(N)] P = [-1] * N Q = deque([0]) R = [] while Q: i = deque.popleft(Q) R.append(i) for a in E[i]: if a != P[i]: P[a] = i E[a].remove(i) deque.append(Q, a) C = [[] for _ in range(N)] def calclist(p, L): L = sorted(L) while L and L[-1] > p: p -= L.pop() if L: if L[-1] > - (1 << 50): p += L.pop() else: while L: p += L.pop() + ((1 << 50) if p < - (1 << 50) else 0) else: p -= 1 << 50 return [p] return [p] + L def summ(L): p = 0 L = sorted(L) while L: if L[-1] > - (1 << 50): p += L.pop() if L: if L[-1] > - (1 << 50): p -= L.pop() else: p -= sum([a + (1 << 50) for a in L]) L = [] else: p += sum([a + (1 << 50) for a in L]) L = [] return p for i in R[::-1]: t = calclist(A[i], C[i]) if P[i] >= 0: C[P[i]] += t else: print(summ(t))