#include <bits/stdc++.h>
using namespace std;
vector<int> edge[200005];
long long res = 0, ans = 0;
int val[200005];
long long sum[200005];
void dfs(int u, int p, int lev) {
  res += 1ll * lev * val[u];
  sum[u] = val[u];
  for (int v : edge[u]) {
    if (v != p) {
      dfs(v, u, lev + 1);
      sum[u] += sum[v];
    }
  }
}
void rec(int u, int p) {
  ans = max(ans, res);
  for (int v : edge[u]) {
    if (v == p) continue;
    long long tmp = res;
    long long niche = sum[v];
    long long upore = sum[1] - sum[v];
    res += upore;
    res -= niche;
    rec(v, u);
    res = tmp;
  }
}
int main() {
  int n;
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) scanf("%d", &val[i]);
  for (int i = 1; i < n; i++) {
    int u, v;
    scanf("%d %d", &u, &v);
    edge[u].push_back(v);
    edge[v].push_back(u);
  }
  dfs(1, -1, 0);
  rec(1, -1);
  printf("%lld\n", ans);
  return 0;
}
