#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr);
  long long n;
  cin >> n;
  vector<long long> a((size_t)n);
  for (long long i = 0; i < n; i++) {
    cin >> a[i];
  }
  vector<vector<long long>> adj((size_t)n);
  for (long long i = 0; i < n - 1; i++) {
    long long u, v;
    cin >> u >> v;
    u--, v--;
    adj[u].push_back(v);
    adj[v].push_back(u);
  }
  long long sum = 0;
  vector<long long> sub((size_t)n, 0);
  function<void(long long, long long, long long)> visit_1 =
      [&](long long u, long long v, long long d) {
        sum += a[v] * d;
        sub[v] += a[v];
        for (long long w : adj[v]) {
          if (w != u) {
            visit_1(v, w, d + 1);
            sub[v] += sub[w];
          }
        }
      };
  visit_1(-1, 0, 0);
  long long all = accumulate(a.begin(), a.end(), (long long)0);
  long long ans = 0;
  function<void(long long, long long)> visit_2 = [&](long long u, long long v) {
    ans = max(ans, sum);
    for (long long w : adj[v]) {
      if (w != u) {
        sum += all - sub[w];
        sum -= sub[w];
        visit_2(v, w);
        sum += sub[w];
        sum -= all - sub[w];
      }
    }
  };
  visit_2(-1, 0);
  cout << ans << endl;
  return 0;
}
