#include <bits/stdc++.h>
using namespace std;
vector<int> G[200005];
int n, a[200005], fa[200005];
long long sum[200005], sons[200005], tuo[200005], he;
void dfs(int now) {
  sons[now] = a[now];
  for (int i = 0; i < G[now].size(); i++) {
    int to = G[now][i];
    if (to == fa[now]) continue;
    fa[to] = now;
    dfs(to);
    sum[now] = sum[to] + sons[to] + sum[now];
    sons[now] += sons[to];
  }
}
long long ans = 0;
void dfs1(int now) {
  for (int i = 0; i < G[now].size(); i++) {
    int to = G[now][i];
    if (to == fa[now]) continue;
    sum[to] = (he - sons[to]) + sum[now] - sons[to];
    ans = max(ans, sum[to]);
    dfs1(to);
  }
}
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) {
    scanf("%d", &a[i]);
    he += a[i];
  }
  for (int i = 1; i < n; i++) {
    int u, v;
    scanf("%d%d", &u, &v);
    G[u].push_back(v);
    G[v].push_back(u);
  }
  dfs(1);
  ans = sum[1];
  dfs1(1);
  printf("%lld\n", ans);
  return 0;
}
