#include <bits/stdc++.h>
using namespace std;
const double eps = 1e-6;
const int mod = 1e9 + 7;
const int maxn = 2e6 + 100;
const int maxm = 2e6 + 100;
const int inf = 0x3f3f3f3f;
const double pi = acos(-1.0);
vector<int> g[maxn];
int a[maxn];
long long res, ans;
long long sum[maxn];
void dfs(int x, int fa, int h) {
  int sz = g[x].size();
  res += 1ll * h * a[x];
  sum[x] = a[x];
  for (int i = 0; i < sz; i++) {
    if (g[x][i] == fa) continue;
    dfs(g[x][i], x, h + 1);
    sum[x] += sum[g[x][i]];
  }
  return;
}
void dfs2(int x, int fa) {
  ans = max(res, ans);
  int sz = g[x].size();
  for (int i = 0; i < sz; i++) {
    int y = g[x][i];
    if (y == fa) continue;
    res -= sum[y];
    sum[x] -= sum[y];
    res += sum[x];
    sum[y] += sum[x];
    dfs2(y, x);
    sum[y] -= sum[x];
    res -= sum[x];
    sum[x] += sum[y];
    res += sum[y];
  }
  return;
}
int main() {
  int n;
  scanf("%d", &n);
  memset(sum, 0, sizeof(sum));
  for (int i = 1; i <= n; i++) {
    scanf("%d", &a[i]);
  }
  for (int i = 1; i < n; i++) {
    int x, y;
    scanf("%d %d", &x, &y);
    g[x].push_back(y);
    g[y].push_back(x);
  }
  res = 0;
  ans = 0;
  dfs(1, -1, 0);
  dfs2(1, -1);
  printf("%lld", ans);
  return 0;
}
