#include <bits/stdc++.h>
using namespace std;
long long res, sum;
void dfs(bool b[], vector<long long> adj[], long long levels[], long long u,
         long long sums[], long long a[]) {
  b[u] = true;
  sums[u] = a[u];
  vector<long long>::iterator it;
  for (it = adj[u].begin(); it != adj[u].end(); it++) {
    if (!b[(*it)]) {
      levels[(*it)] = levels[u] + 1;
      dfs(b, adj, levels, (*it), sums, a);
      sums[u] += sums[(*it)];
    }
  }
}
void dfs2(vector<long long> adj[], bool b[], long long sc, long long u,
          long long sums[]) {
  res = max(res, sc);
  b[u] = true;
  vector<long long>::iterator it;
  for (it = adj[u].begin(); it != adj[u].end(); it++) {
    if (!b[(*it)]) {
      long long temp = sc - 2 * sums[(*it)] + sum;
      dfs2(adj, b, temp, (*it), sums);
    }
  }
}
int main() {
  long long n;
  cin >> n;
  long long *a = new long long[n + 1];
  for (long long i = 1; i <= n; i++) {
    cin >> a[i];
  }
  vector<long long> adj[n + 1];
  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);
  }
  long long levels[n + 1];
  bool b[n + 1];
  for (long long i = 1; i <= n; i++) {
    b[i] = false;
  }
  levels[1] = 0;
  long long sums[n + 1];
  dfs(b, adj, levels, 1, sums, a);
  for (long long i = 1; i <= n; i++) {
    res += levels[i] * a[i];
    sum += a[i];
  }
  for (long long i = 1; i <= n; i++) {
    b[i] = false;
  }
  long long sc = res;
  dfs2(adj, b, sc, 1, sums);
  cout << res << "\n";
}
