#include <bits/stdc++.h>
using namespace std;
struct edge {
  int to, next;
  edge(int to = 0, int next = 0) : to(to), next(next) {}
} es[200010 * 2];
int head[200010], ecnt, n;
long long a[200010], sum[200010], dp[200010], ans = 0;
void add(int from, int to) {
  es[++ecnt] = edge(to, head[from]), head[from] = ecnt;
}
void init() {
  memset(head, 0, sizeof(head[0]) * (n + 2));
  ecnt = 0;
}
void dfs1(int root, int par, int step) {
  dp[1] += 1LL * step * a[root];
  sum[root] = a[root];
  for (int i = head[root]; i != 0; i = es[i].next) {
    int to = es[i].to;
    if (to != par) {
      dfs1(to, root, step + 1);
      sum[root] += sum[to];
    }
  }
}
void dfs2(int root, int par) {
  for (int i = head[root]; i != 0; i = es[i].next) {
    int to = es[i].to;
    if (to != par) {
      dp[to] = dp[root] - sum[to] + (sum[1] - sum[to]);
      ans = max(ans, dp[to]);
      dfs2(to, root);
    }
  }
}
int main() {
  scanf("%d", &n);
  init();
  for (int i = 1; i <= n; ++i) scanf("%lld", a + i);
  for (int i = 1, u, v; i < n; ++i) {
    scanf("%d%d", &u, &v);
    add(u, v);
    add(v, u);
  }
  dfs1(1, 0, 0);
  ans = max(ans, dp[1]);
  dfs2(1, 0);
  cout << ans << endl;
  return 0;
}
