#include <bits/stdc++.h>
using namespace std;
long long rr[] = {0, 1, 1, 1, 0, -1, -1, -1};
long long cc[] = {1, 1, 0, -1, -1, -1, 0, 1};
const long long mod = 1e9 + 7;
const long long N = 300050;
long long n, a[N], dis[N], val[N], nodeans[N], ans = 0;
vector<vector<long long> > adj(N);
vector<long long> vis(N);
void dfs(long long v) {
  vis[v] = 1;
  val[v] += a[v];
  for (long long u : adj[v]) {
    if (!vis[u]) {
      dis[u] = dis[v] + 1;
      dfs(u);
      val[v] += val[u];
    }
  }
}
signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  ;
  long long test = 1;
  while (test--) {
    cin >> n;
    for (long long i = 1; i <= n; i++) {
      cin >> a[i];
    }
    for (long long i = 1; i < n; i++) {
      long long x, y;
      cin >> x >> y;
      adj[x].push_back(y);
      adj[y].push_back(x);
    }
    dfs(1);
    for (long long i = 1; i <= n; i++) {
      ans += dis[i] * a[i];
      vis[i] = 0;
    }
    nodeans[1] = ans;
    long long tot = val[1];
    queue<long long> q;
    q.push(1);
    while (q.size()) {
      long long v = q.front();
      vis[v] = 1;
      q.pop();
      for (long long u : adj[v]) {
        if (!vis[u]) {
          nodeans[u] = nodeans[v] + (tot - 2 * val[u]);
          ans = max(ans, nodeans[u]);
          q.push(u);
        }
      }
    }
    cout << ans << '\n';
  }
  return 0;
}
