#include <bits/stdc++.h>
using namespace std;
const long long maxn = 200005;
long long n;
long long a[maxn];
vector<long long> adj[maxn];
long long dp[maxn];
long long dep[maxn], sts[maxn];
bool vis[maxn];
void dfs1(long long u) {
  sts[u] = a[u];
  for (long long i = 0; i < adj[u].size(); i++) {
    long long v = adj[u][i];
    if (dep[v] != -1) continue;
    dep[v] = dep[u] + 1;
    dfs1(v);
    sts[u] += sts[v];
  }
}
void dfs2(long long u) {
  vis[u] = 1;
  for (long long i = 0; i < adj[u].size(); i++) {
    long long v = adj[u][i];
    if (vis[v]) continue;
    dp[v] = dp[u] - sts[v] + sts[1] - sts[v];
    dfs2(v);
  }
}
signed main() {
  memset(dep, -1, sizeof(dep));
  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;
    adj[u].push_back(v);
    adj[v].push_back(u);
  }
  dep[1] = 0;
  dfs1(1);
  for (long long i = 1; i <= n; i++) dp[1] += dep[i] * a[i];
  dfs2(1);
  long long ans = 0;
  for (long long i = 1; i <= n; i++) ans = max(ans, dp[i]);
  cout << ans;
  return 0;
}
