#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 10;
struct Edge {
  int v, nxt;
} e[N << 1];
int fst[N], ne = 0;
void addedge(int u, int v) {
  e[ne].v = v;
  e[ne].nxt = fst[u];
  fst[u] = ne++;
}
long long sum[N], f[N], a[N], ans = -1ll;
int n;
void build(int x, int fa) {
  sum[x] = a[x];
  f[x] = 0ll;
  for (int i = fst[x]; i != -1; i = e[i].nxt) {
    int v = e[i].v;
    if (v == fa) continue;
    build(v, x);
    sum[x] += sum[v];
    f[x] += f[v] + sum[v];
  }
}
void dfs(int x, int fa) {
  ans = max(ans, f[x]);
  for (int i = fst[x]; i != -1; i = e[i].nxt) {
    int v = e[i].v;
    if (v == fa) continue;
    long long sx = sum[x], sv = sum[v], fx = f[x], fv = f[v];
    f[x] -= sum[v] + f[v];
    sum[x] -= sum[v];
    f[v] += f[x] + sum[x];
    sum[v] = sx;
    dfs(v, x);
    sum[x] = sx;
    sum[v] = sv;
    f[x] = fx;
    f[v] = fv;
  }
}
int main() {
  memset(fst, -1, sizeof(fst));
  cin >> n;
  for (int i = 1; i <= n; i++) {
    cin >> a[i];
  }
  int u, v;
  for (int i = 1; i < n; i++) {
    cin >> u >> v;
    addedge(u, v);
    addedge(v, u);
  }
  build(1, -1);
  dfs(1, -1);
  cout << ans << endl;
  return 0;
}
