#include <bits/stdc++.h>
using namespace std;
int n, a[200010];
vector<int> G[200010];
long long res = 0;
long long tot;
int fa[200010];
long long f[200010], g[200010], sum[200010];
void DFS1(int u) {
  sum[u] = a[u];
  f[u] = 0;
  for (auto v : G[u])
    if (v != fa[u]) {
      fa[v] = u;
      DFS1(v);
      sum[u] += sum[v];
      f[u] += f[v] + sum[v];
    }
}
void DFS2(int u) {
  res = max(res, f[u] + g[u]);
  for (auto v : G[u])
    if (v != fa[u]) {
      g[v] = g[u] + f[u] - f[v] + tot - 2 * sum[v];
      DFS2(v);
    }
}
int main() {
  while (scanf("%d", &n) != EOF) {
    for (int i = 1; i <= n; ++i) G[i].clear();
    tot = 0;
    res = 0;
    g[1] = 0;
    for (int i = 1; i <= n; ++i) scanf("%d", a + i), tot += a[i];
    for (int i = 1, u, v; i < n; ++i) {
      scanf("%d%d", &u, &v);
      G[u].push_back(v);
      G[v].push_back(u);
    }
    DFS1(1), DFS2(1);
    printf("%lld\n", res);
  }
  return 0;
}
