#include <bits/stdc++.h>
using namespace std;
const int MAXN = 200005, MAXM = 400005;
struct Edge {
  int to, next;
} edge[MAXM];
int head[MAXN], a[MAXN], n, tot = 1;
long long sum[MAXN], ans, vs;
void addedge(int u, int v) {
  edge[tot] = (Edge){v, head[u]};
  head[u] = tot++;
}
void dfs1(int u, int dep, int fa) {
  sum[u] = a[u], vs += (long long)dep * a[u];
  for (int i = head[u]; i; i = edge[i].next) {
    int v = edge[i].to;
    if (v != fa) {
      dfs1(v, dep + 1, u);
      sum[u] += sum[v];
    }
  }
}
void dfs2(int u, int fa, long long cur) {
  ans = max(ans, cur);
  for (int i = head[u]; i; i = edge[i].next) {
    int v = edge[i].to;
    if (v != fa) dfs2(v, u, cur + sum[1] - 2ll * sum[v]);
  }
}
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) scanf("%d", a + i);
  for (int i = 1; i < n; i++) {
    int u, v;
    scanf("%d%d", &u, &v);
    addedge(u, v), addedge(v, u);
  }
  dfs1(1, 0, 0), dfs2(1, 0, vs);
  printf("%lld\n", ans);
  return 0;
}
