#include <bits/stdc++.h>
using namespace std;
inline void file() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  if (0) {
    freopen(".in", "r", stdin);
    freopen(".out", "w", stdout);
  }
}
const int PX[8] = {1, 0, -1, 0, 1, 1, -1, -1},
          PY[8] = {0, 1, 0, -1, -1, 1, 1, -1}, N = 2e5 + 10, INF = 1e9,
          MOD = 1e9 + 7;
const long long INFL = 1e18, MODL = 1e9 + 7;
const long double EPS = 1e-6;
template <typename type>
inline void up(type& a, type b) {
  if (a < b) a = b;
}
inline long long rnd(long long l = 1, long long r = INFL) {
  unsigned long long ans = rand();
  ans = (ans << 16LL) ^ rand();
  ans = (ans << 16LL) ^ rand();
  ans = (ans << 16LL) ^ rand();
  ans %= r - l + 1;
  return (long long)ans + l;
}
int n;
long long res, sumW, w[N], sz[N], d[N];
vector<int> g[N];
long long dfs(int v, int pred) {
  sz[v] = w[v];
  if (pred) d[v] = d[pred] + 1;
  for (int i : g[v])
    if (i != pred) sz[v] += dfs(i, v);
  return sz[v];
}
void dfs2(int v, int pred, long long now) {
  if (res < now) res = now;
  for (int i : g[v]) {
    if (i == pred) continue;
    dfs2(i, v, now + sumW - 2 * sz[i]);
  }
}
int main() {
  file();
  scanf("%d", &n);
  for (int i = 1; i <= n; ++i) {
    scanf("%d", &w[i]);
    sumW += w[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);
  }
  dfs(1, 0);
  long long all = 0;
  for (int i = 1; i <= n; ++i) all += (long long)d[i] * w[i];
  dfs2(1, 0, all);
  cout << res << '\n';
}
