#include <bits/stdc++.h>
using namespace std;
const long long inf = 0x3f3f3f3f3f3f3f3f, N = 2e5 + 5;
long long n, a[N], sub[N], dp[N];
vector<long long> g[N];
long long dfs(long long v, long long p) {
  long long rtn = 0;
  sub[v] = a[v];
  for (long long u : g[v]) {
    if (u == p) continue;
    long long x = dfs(u, v);
    sub[v] += sub[u];
    rtn += x + sub[u];
  }
  return dp[v] = rtn;
}
void _dfs(long long v, long long p) {
  for (long long u : g[v]) {
    if (u == p) continue;
    long long val = dp[v];
    val -= (dp[u] + sub[u]);
    dp[u] += (val + sub[1ll] - sub[u]);
    _dfs(u, v);
  }
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  ;
  cin >> n;
  for (long long i = 1; i <= n; i++) cin >> a[i];
  for (long long i = 1; i < n; i++) {
    long long u, v;
    cin >> u >> v;
    g[u].push_back(v);
    g[v].push_back(u);
  }
  dfs(1, 0);
  _dfs(1, 0);
  long long ans = 0;
  for (long long i = 1; i <= n; i++) ans = max(ans, dp[i]);
  cout << ans;
  return 0;
}
