#include <bits/stdc++.h>
using namespace std;
const int Maxn = 2e5 + 100;
int head[Maxn], n, a[Maxn], g[2 * Maxn], nxt[2 * Maxn], cnt;
void addedge(int x, int y) {
  cnt++, g[cnt] = y, nxt[cnt] = head[x], head[x] = cnt;
}
long long sum[Maxn], s, dp[Maxn], ans;
void dfs(int x, int fa) {
  sum[x] = a[x];
  for (int i = head[x]; i; i = nxt[i]) {
    if (g[i] != fa) {
      dfs(g[i], x);
      sum[x] += sum[g[i]];
      dp[x] = dp[x] + dp[g[i]] + sum[g[i]];
    }
  }
}
void dfs2(int x, int fa) {
  for (int i = head[x]; i; i = nxt[i]) {
    if (g[i] != fa) {
      dp[g[i]] = dp[x] - sum[g[i]] + s - sum[g[i]];
      ans = max(ans, dp[g[i]]);
      dfs2(g[i], x);
    }
  }
}
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) {
    scanf("%d", &a[i]);
    s += a[i];
  }
  for (int i = 1; i < n; i++) {
    int x, y;
    scanf("%d %d", &x, &y);
    addedge(x, y);
    addedge(y, x);
  }
  dfs(1, 0);
  ans = max(ans, dp[1]);
  dfs2(1, 0);
  cout << ans;
  return 0;
}
