#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int mxN = 1e6 + 5, mod = 1e9 + 7, LOG = 20;
int n, a[mxN];
ll sum[mxN], dp[mxN], mda, ans;
vector<int> adj[mxN];
void dfs(int v, int p = 0) {
  sum[v] = a[v];
  for (auto to : adj[v]) {
    if (to != p) {
      dfs(to, v);
      dp[v] += dp[to] + sum[to];
      sum[v] += sum[to];
    }
  }
}
void go(int v, int p = 0) {
  ans = max(ans, dp[v]);
  for (auto to : adj[v]) {
    if (to != p) {
      dp[v] -= dp[to] + sum[to];
      sum[v] -= sum[to];
      dp[to] += dp[v] + sum[v];
      sum[to] += sum[v];
      go(to, v);
      dp[to] -= dp[v] + sum[v];
      sum[to] -= sum[v];
      dp[v] += dp[to] + sum[to];
      sum[v] += sum[to];
    }
  }
}
void solve() {
  cin >> n;
  for (int i = 1; i <= n; ++i) cin >> a[i], mda += a[i];
  for (int i = 1, u, v; i < n; ++i) {
    cin >> u >> v;
    adj[u].push_back(v);
    adj[v].push_back(u);
  }
  dfs(1);
  go(1);
  cout << ans;
}
int main() {
  ios ::sync_with_stdio(false), cin.tie(nullptr);
  int t = 1;
  while (t--) {
    solve();
    cout << '\n';
  }
  return 0;
}
