#include <bits/stdc++.h>
using namespace std;
long long power(long long, long long);
long long mpower(long long, long long);
long long BIT[1000009];
long long query(long long);
void update(long long, long long);
vector<long long> graph[1000009];
;
long long ans[1000009], dp[1000009], num[1000009];
long long val[1000009], n;
void dfs1(long long v, long long p) {
  for (long long u : graph[v]) {
    if (u != p) {
      dfs1(u, v);
      dp[v] += dp[u] + num[u];
      num[v] += num[u];
    }
  }
  num[v] += val[v];
}
void dfs2(long long v, long long p) {
  if (p != 0) {
    long long last = num[p] - num[v];
    long long l = dp[p] - dp[v] - num[v];
    num[v] += last;
    dp[v] += l + last;
  }
  ans[v] = dp[v];
  for (long long u : graph[v]) {
    if (u != p) {
      dfs2(u, v);
    }
  }
}
int32_t main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  cin >> n;
  for (long long i = 1; i <= n; i++) {
    cin >> val[i];
  }
  for (long long i = 0; i < n - 1; i++) {
    long long a, b;
    cin >> a >> b;
    graph[a].push_back(b);
    graph[b].push_back(a);
  }
  dfs1(1, 0);
  dfs2(1, 0);
  cout << *max_element(ans + 1, ans + n + 1);
  return 0;
}
void update(long long x, long long delta) {
  for (; x < 1000009; x += x & -x) BIT[x] += delta;
}
long long query(long long x) {
  long long sum = 0;
  for (; x > 0; x -= x & -x) sum += BIT[x];
  return sum;
}
long long power(long long a, long long b) {
  long long res = 1;
  while (b > 0) {
    if (b % 2 == 1) res = res * a;
    a = a * a;
    b = b / 2;
  }
  return res;
}
long long mpower(long long a, long long b) {
  long long res = 1;
  while (b > 0) {
    if (b % 2 == 1) {
      res = (res * a) % 1000000007;
    }
    a = (a * a) % 1000000007;
    b = b / 2;
  }
  return res;
}
