#include <bits/stdc++.h>
using namespace std;
vector<long long> v[200001];
long long a[200001], dp[200001];
long long sum[200001], ans = 0;
void dfs(long long s, long long p, long long l) {
  long long val = a[s];
  ans += (a[s] * l);
  for (auto i : v[s]) {
    if (i == p) continue;
    dfs(i, s, l + 1);
    val += sum[i];
  }
  sum[s] = val;
}
void call(long long s, long long p) {
  long long val = 0;
  if (p) {
    val = dp[p] - sum[s] + (sum[1] - sum[s]);
    dp[s] = val;
    ans = max(ans, val);
  }
  for (auto i : v[s]) {
    if (i == p) continue;
    call(i, s);
  }
}
int main() {
  long long i, j, k, x, t, y, n, m;
  cin >> n;
  for (i = 1; i <= n; i++) cin >> a[i];
  t = n - 1;
  while (t--) {
    cin >> x >> y;
    v[x].push_back(y);
    v[y].push_back(x);
  }
  dfs(1, 0, 0);
  dp[1] = ans;
  call(1, 0);
  cout << ans;
  return 0;
}
