#include <bits/stdc++.h>
std::vector<int> e[200005];
int a[200005], n;
long long sum[200005], ans, cur, tot;
void dfs(int x, int p, int l) {
  sum[x] += a[x];
  cur += 1ll * l * a[x];
  for (int i = 0; i < e[x].size(); ++i) {
    if (e[x][i] == p) continue;
    dfs(e[x][i], x, l + 1);
    sum[x] += sum[e[x][i]];
  }
}
void dfs2(int x, int p) {
  ans = std::max(ans, cur);
  for (int i = 0; i < e[x].size(); ++i) {
    if (e[x][i] == p) continue;
    cur += tot - 2 * sum[e[x][i]];
    dfs2(e[x][i], x);
    cur -= tot - 2 * sum[e[x][i]];
  }
}
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; ++i) {
    scanf("%d", a + i);
    tot += a[i];
  }
  for (int i = 0, u, v; i < n - 1; ++i) {
    scanf("%d %d", &u, &v);
    e[u].push_back(v);
    e[v].push_back(u);
  }
  dfs(1, -1, 0);
  tot = sum[1];
  dfs2(1, -1);
  printf("%I64d\n", ans);
  return 0;
}
