#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 10;
inline int read() {
  int x = 0, f = 1;
  char ch = getchar();
  while (ch < '0' || ch > '9') {
    if (ch == '-') f = -1;
    ch = getchar();
  }
  while (ch >= '0' && ch <= '9') {
    x = (x << 1) + (x << 3) + (ch ^ 48);
    ch = getchar();
  }
  return x * f;
}
int n, head[N], cnt;
long long siz[N], sum, f[N], ans = 0, a[N], dep[N];
struct edge {
  int nxt, to;
} e[N << 1];
inline void add(int x, int y) {
  e[++cnt].nxt = head[x];
  e[cnt].to = y;
  head[x] = cnt;
}
inline void dfs1(int x, int fa) {
  siz[x] = a[x];
  for (int i = head[x]; i; i = e[i].nxt) {
    int v = e[i].to;
    if (v == fa) continue;
    dep[v] = dep[x] + 1;
    f[1] = f[1] + (long long)(a[v] * dep[v]);
    dfs1(v, x);
    siz[x] += siz[v];
  }
}
inline void dfs2(int x, int fa) {
  for (int i = head[x]; i; i = e[i].nxt) {
    int y = e[i].to;
    if (y == fa) continue;
    f[y] = f[x] + sum - siz[y] - siz[y];
    dfs2(y, x);
  }
}
int main() {
  n = read();
  for (int i = 1; i <= n; i++) {
    a[i] = read();
    sum += a[i];
  }
  for (int i = 1; i < n; i++) {
    int u, v;
    u = read(), v = read();
    add(u, v);
    add(v, u);
  }
  dfs1(1, 0);
  dfs2(1, 0);
  for (int i = 1; i <= n; i++) {
    ans = max(f[i], ans);
  }
  printf("%lld", ans);
  return 0;
}
