#include <bits/stdc++.h>
using namespace std;
const int MAXN = 2 * 100100;
int n, a[MAXN];
long long subsum[MAXN], f[MAXN];
long long ans = 0;
vector<int> g[MAXN];
void dfs(int v, int p = -1) {
  for (const int& u : g[v])
    if (u != p) dfs(u, v), subsum[v] += subsum[u], f[v] += f[u];
  f[v] += subsum[v], subsum[v] += a[v];
}
void solve(int v, long long x, int p = -1) {
  ans = max(ans, x);
  for (const int& u : g[v])
    if (u != p) solve(u, x + subsum[1] - 2 * subsum[u], v);
}
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; ++i) scanf("%d", &a[i]);
  for (int i = 1, u, v; i < n; ++i)
    scanf("%d %d", &u, &v), g[u].push_back(v), g[v].push_back(u);
  dfs(1), solve(1, f[1]);
  printf("%lld\n", ans);
}
