#include <bits/stdc++.h>
using namespace std;
long long ans = 0, m, a[2000005], sum[2000005];
vector<long long> adj[2000005];
void dfs(long long i, long long p) {
  sum[i] = a[i];
  for (auto k : adj[i]) {
    if (k == p) continue;
    dfs(k, i);
    sum[i] += sum[k];
    ans += sum[k];
  }
}
void dfs2(long long i, long long p) {
  for (auto j : adj[i]) {
    if (j == p) continue;
    ans -= sum[j];
    sum[i] -= sum[j];
    ans += sum[i];
    sum[j] += sum[i];
    m = max(m, ans);
    dfs2(j, i);
    sum[j] -= sum[i];
    ans -= sum[i];
    sum[i] += sum[j];
    ans += sum[j];
  }
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  int t = 1;
  while (t--) {
    long long n, i, j;
    cin >> n;
    for (i = 1; i < 1 + 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);
    m = ans;
    dfs2(1, 0);
    cout << m << " ";
  }
  return 0;
}
