#include <bits/stdc++.h>
using namespace std;
long long n, res = 0, ans = 0;
long long arr[211111], dp[211111];
vector<long long> tree[211111];
void dfs(long long v, long long par = -1, long long height = 0) {
  res += arr[v] * height;
  dp[v] = arr[v];
  for (long long u : tree[v]) {
    if (u != par) {
      dfs(u, v, height + 1);
      dp[v] += dp[u];
    }
  }
}
void go(long long v, long long par = -1) {
  ans = max(ans, res);
  for (long long itr : tree[v]) {
    if (itr != par) {
      res -= dp[itr];
      dp[v] -= dp[itr];
      dp[itr] += dp[v];
      res += dp[v];
      go(itr, v);
      dp[itr] -= dp[v];
      res -= dp[v];
      dp[v] += dp[itr];
      res += dp[itr];
    }
  }
}
signed main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  cin >> n;
  for (long long i = 1; i <= n; i++) {
    cin >> arr[i];
  }
  for (long long i = 1; i < n; i++) {
    long long u, v;
    cin >> u >> v;
    tree[u].push_back(v);
    tree[v].push_back(u);
  }
  dfs(1);
  go(1);
  cout << ans << endl;
  return 0;
}
