#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 10;
struct Edge {
  int to, nxt;
} e[N << 1];
int h[N], idx, a[N];
void Ins(int a, int b) {
  e[++idx].to = b;
  e[idx].nxt = h[a];
  h[a] = idx;
}
long long dis[N], siz[N];
void dfs(int u, int fa) {
  siz[u] = a[u];
  for (int i = h[u]; i; i = e[i].nxt) {
    int v = e[i].to;
    if (v == fa) continue;
    dfs(v, u);
    siz[u] += siz[v];
    dis[1] += siz[v];
  }
}
long long sum;
void dfs1(int u, int fa) {
  for (int i = h[u]; i; i = e[i].nxt) {
    int v = e[i].to;
    if (v == fa) continue;
    dis[v] = dis[u] + sum - 2ll * siz[v];
    dfs1(v, u);
  }
}
int main() {
  int n;
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) scanf("%d", &a[i]), sum += a[i];
  for (int i = 2; i <= n; i++) {
    int x, y;
    scanf("%d%d", &x, &y);
    Ins(x, y);
    Ins(y, x);
  }
  dfs(1, 0);
  dfs1(1, 0);
  long long res = 0;
  for (int i = 1; i <= n; i++) res = max(res, dis[i]);
  printf("%lld\n", res);
  return 0;
}
