#include <bits/stdc++.h>
using namespace std;
long long Head[400000 + 5], Cnt, N, A[400000 + 5], sigma, F[400000 + 5],
    S[400000 + 5];
struct Edge {
  long long Next, To;
} E[400000 << 2];
void Add_Edge(long long X, long long Y) {
  E[++Cnt].Next = Head[X];
  E[Cnt].To = Y, Head[X] = Cnt;
}
void DFS1(long long X, long long Fa) {
  S[X] = A[X];
  for (long long I = Head[X]; I; I = E[I].Next) {
    long long Y = E[I].To;
    if (Y == Fa) continue;
    DFS1(Y, X), S[X] += S[Y];
    F[X] += F[Y] + S[Y];
  }
}
void DFS2(long long X, long long Fa) {
  for (long long I = Head[X]; I; I = E[I].Next) {
    long long Y = E[I].To;
    if (Y == Fa) continue;
    F[Y] = F[X] - S[Y] + (sigma - S[Y]);
    DFS2(Y, X);
  }
}
signed main() {
  scanf("%lld", &N);
  for (long long I = 1; I <= N; I++) scanf("%lld", &A[I]), sigma += A[I];
  for (long long I = 1; I < N; I++) {
    long long U, V;
    scanf("%lld%lld", &U, &V);
    Add_Edge(U, V), Add_Edge(V, U);
  }
  DFS1(1, 0), DFS2(1, 0);
  long long pos = 0, v = 0;
  for (long long I = 1; I <= N; I++)
    if (v < F[I]) v = F[I], pos = I;
  printf("%lld\n", F[pos]);
  return 0;
}
