#include <bits/stdc++.h>
using namespace std;
vector<vector<int> > mv;
vector<long long> a;
vector<int> d;
vector<long long> sum;
long long to;
long long res;
long long fi(int ac, int le, int fa) {
  d[ac] = le;
  int i, s = mv[ac].size();
  long long ret = a[ac];
  for (i = 0; i < s; i++)
    if (mv[ac][i] != fa) ret += fi(mv[ac][i], le + 1, ac);
  return sum[ac] = ret;
}
void re(int ac, int fa, long long can) {
  if (can > res) res = can;
  int i, s = mv[ac].size();
  for (i = 0; i < s; i++)
    if (mv[ac][i] != fa) re(mv[ac][i], ac, can + to - sum[mv[ac][i]] * 2);
}
int main() {
  int n;
  scanf("%d", &n);
  a.resize(n);
  mv.resize(n);
  sum.resize(n);
  d.resize(n);
  int i;
  to = 0;
  for (i = 0; i < n; i++) scanf("%lld", &a[i]), to += a[i];
  for (i = 1; i < n; i++) {
    int u, v;
    scanf("%d %d", &u, &v);
    u--;
    v--;
    mv[u].push_back(v);
    mv[v].push_back(u);
  }
  res = 0;
  fi(0, 0, -1);
  for (i = 0; i < n; i++) res += a[i] * d[i];
  re(0, -1, res);
  printf("%lld\n", res);
  return 0;
}
