#include <bits/stdc++.h>
using namespace std;
const long long gsize = 2e5 + 5;
vector<long long> adj[gsize];
long long a[gsize], stsum[gsize];
long long res, ans;
long long dfs(long long cur, long long par, long long ht) {
  res += (ht * a[cur]);
  long long sum = a[cur];
  for (auto x : adj[cur]) {
    if (x == par) continue;
    sum += dfs(x, cur, ht + 1);
  }
  return stsum[cur] = sum;
}
void calc(long long cur, long long par, long long out, long long res) {
  if (par != 0) {
    res -= stsum[cur];
    res += (stsum[par] - stsum[cur]);
    res += out;
    ans = max(ans, res);
  }
  for (auto x : adj[cur]) {
    if (x == par) continue;
    long long tmpout = 0;
    if (par != 0) tmpout = stsum[par] - stsum[cur];
    calc(x, cur, out + tmpout, res);
  }
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  long long n, m, i, j, k;
  cin >> n;
  for (i = 1; i <= n; i++) cin >> a[i];
  for (i = 0; i < n - 1; i++) {
    long long u, v;
    cin >> u >> v;
    adj[u].push_back(v);
    adj[v].push_back(u);
  }
  dfs(1, 0, 0);
  ans = res;
  calc(1, 0, 0, res);
  cout << ans;
  return 0;
}
