#include <bits/stdc++.h>
using namespace std;
const int MAXN = 2e5 + 10;
vector<int> g[MAXN];
int n;
long long f[MAXN], a[MAXN], S, sum[MAXN], maxf;
void dfs(int x, int d, int fa) {
  f[1] = f[1] + (long long)d * a[x];
  sum[x] = sum[x] + a[x];
  int i, y, len = g[x].size();
  for (i = 0; i < len; i++) {
    y = g[x][i];
    if (y != fa) {
      dfs(y, d + 1, x);
      sum[x] += sum[y];
    }
  }
  return;
}
void dfs2(int x, int fa) {
  int i, y, len = g[x].size();
  for (i = 0; i < len; i++) {
    y = g[x][i];
    if (y != fa) {
      f[y] = f[x] + (S - sum[y]) - sum[y];
      dfs2(y, x);
    }
  }
  return;
}
inline int read() {
  int sum = 0;
  char ch = getchar();
  while (ch < '0' || ch > '9') ch = getchar();
  while (ch >= '0' && ch <= '9') sum = sum * 10 + ch - 48, ch = getchar();
  return sum;
}
int main() {
  n = read();
  int i, u, v;
  for (i = 1; i <= n; i++) a[i] = read(), S += a[i];
  for (i = 1; i < n; i++) {
    u = read();
    v = read();
    g[u].push_back(v);
    g[v].push_back(u);
  }
  dfs(1, 0, 0);
  dfs2(1, 0);
  for (i = 1; i <= n; i++)
    if (f[i] > maxf) maxf = f[i];
  cout << maxf;
  return 0;
}
