#include <bits/stdc++.h>
using namespace std;
const int N = 5e5;
struct E {
  int t, next;
} e[N];
int head[N];
long long sum[N], v[N];
int n, cnt;
long long all, ans, tot;
void add(int u, int v) {
  e[cnt].t = v;
  e[cnt].next = head[u];
  head[u] = cnt++;
}
long long dfs1(int now, int f) {
  long long s = 0;
  for (int i = head[now]; ~i; i = e[i].next) {
    if (e[i].t == f) continue;
    s += dfs1(e[i].t, now);
  }
  all += s;
  return sum[now] = v[now] + s;
}
void dfs2(int now, long long nv, int f) {
  if (ans < nv) ans = nv;
  for (int i = head[now]; ~i; i = e[i].next) {
    if (e[i].t == f) continue;
    long long next = nv - 2 * sum[e[i].t] + tot;
    dfs2(e[i].t, next, now);
  }
}
int main() {
  memset(head, -1, sizeof(head));
  memset(sum, 0, sizeof(sum));
  cin >> n;
  for (int i = 1; i <= n; ++i) {
    scanf("%lld", &v[i]);
    tot += v[i];
  }
  int u, v;
  cnt = ans = 0;
  for (int i = 1; i < n; ++i) {
    scanf("%d%d", &u, &v);
    add(u, v);
    add(v, u);
  }
  dfs1(1, -1);
  dfs2(1, all, -1);
  printf("%lld\n", ans);
}
