#include <bits/stdc++.h>
using namespace std;
const long long INF = 1e18;
const long long mod = 1e9 + 7;
const long long N = 2e5 + 10;
inline long long add(long long x, long long y) {
  x += y;
  if (x >= mod) x -= mod;
  return x;
}
inline long long mul(long long x, long long y) {
  x = (1LL * x * y) % mod;
  return x;
}
vector<long long> v[N];
long long val[N];
long long dp[N];
long long vis[N];
long long level[N];
long long res = 0;
long long ans = 0;
void dfs1(long long u) {
  vis[u] = 1;
  res += level[u] * val[u];
  dp[u] += val[u];
  for (auto &x : v[u]) {
    if (vis[x] == 0) {
      level[x] = level[u] + 1;
      dfs1(x);
      dp[u] += dp[x];
    }
  }
}
void dfs2(long long u) {
  ans = max(ans, res);
  vis[u] = 1;
  for (auto &x : v[u]) {
    if (vis[x] == 0) {
      res -= dp[x];
      dp[u] -= dp[x];
      res += dp[u];
      dp[x] += dp[u];
      dfs2(x);
      dp[x] -= dp[u];
      res -= dp[u];
      dp[u] += dp[x];
      res += dp[x];
    }
  }
}
int main() {
  long long n;
  cin >> n;
  for (long long i = 1; i <= n; ++i) cin >> val[i];
  for (long long i = 1; i <= n - 1; ++i) {
    long long x, y;
    cin >> x >> y;
    v[x].push_back(y);
    v[y].push_back(x);
  }
  memset(dp, 0, sizeof(dp));
  dfs1(1);
  ans = res;
  memset(vis, 0, sizeof(vis));
  dfs2(1);
  cout << ans;
  return 0;
}
