#include <bits/stdc++.h>
using namespace std;
void dfs(long long v, vector<vector<long long> >& g, vector<long long>& d,
         vector<long long>& mark, vector<long long>& a,
         vector<long long>& siz) {
  mark[v] = 1;
  siz[v] += a[v];
  for (auto u : g[v]) {
    if (!mark[u]) {
      d[u] = d[v] + 1;
      dfs(u, g, d, mark, a, siz);
      siz[v] += siz[u];
    }
  }
}
void bfs(long long s, vector<vector<long long> >& g, vector<long long>& siz,
         vector<long long>& aa, vector<long long>& a, vector<long long>& mark) {
  long long n = g.size();
  mark.assign(n, 0);
  long long sum = 0;
  for (auto u : a) sum += u;
  mark[s] = 1;
  queue<long long> q;
  q.push(s);
  while (!q.empty()) {
    long long v = q.front();
    q.pop();
    for (auto u : g[v]) {
      if (!mark[u]) {
        mark[u] = 1;
        aa[u] = aa[v] + sum - 2 * siz[u];
        q.push(u);
      }
    }
  }
}
int main() {
  long long n;
  cin >> n;
  vector<vector<long long> > g(n);
  vector<long long> a(n);
  for (long long i = 0; i < n; i++) cin >> a[i];
  long long v, u;
  for (long long i = 0; i < n - 1; i++) {
    cin >> v >> u;
    v--;
    u--;
    g[v].push_back(u);
    g[u].push_back(v);
  }
  vector<long long> d(n), mark(n), siz(n, 0);
  d.assign(n, 0);
  mark.assign(n, 0);
  siz.assign(n, 0);
  dfs(0, g, d, mark, a, siz);
  vector<long long> aa(n);
  aa.assign(n, 0);
  for (long long i = 0; i < n; i++) aa[0] += (d[i] * a[i]);
  bfs(0, g, siz, aa, a, mark);
  long long max = 0;
  for (long long i = 0; i < n; i++)
    if (aa[i] > max) max = aa[i];
  cout << max << "\n";
  return 0;
}
