#include <bits/stdc++.h>
using namespace std;
const int maxn = 200100, maxm = 400100;
struct edge {
  int u, v;
  edge *next;
} epool[maxm], *edges[maxn];
int ecnt;
void add_edge(int u, int v) {
  edge *p = &epool[++ecnt], *q = &epool[++ecnt];
  p->u = u;
  p->v = v;
  p->next = edges[u];
  edges[u] = p;
  q->u = v;
  q->v = u;
  q->next = edges[v];
  edges[v] = q;
  return;
}
int n;
long long a[maxn], asum[maxn];
long long result;
long long dfs_1(int p, int q, long long depth) {
  long long distsum = a[p] * depth;
  asum[p] = a[p];
  for (edge *ep = edges[p]; ep; ep = ep->next)
    if (ep->v != q) {
      distsum += dfs_1(ep->v, p, depth + 1);
      asum[p] += asum[ep->v];
    }
  return distsum;
}
void dfs_2(int p, int q, long long distsum) {
  result = max(result, distsum);
  for (edge *ep = edges[p]; ep; ep = ep->next)
    if (ep->v != q) {
      distsum -= asum[ep->v];
      asum[p] -= asum[ep->v];
      distsum += asum[p];
      asum[ep->v] += asum[p];
      dfs_2(ep->v, p, distsum);
      asum[ep->v] -= asum[p];
      distsum -= asum[p];
      asum[p] += asum[ep->v];
      distsum += asum[ep->v];
    }
  return;
}
int main(int argc, char **argv) {
  scanf("%d", &n);
  for (int i = (1); i <= (n); i++) scanf("%lld", &a[i]);
  for (int i = (1); i <= (n - 1); i++) {
    int x, y;
    scanf("%d%d", &x, &y);
    add_edge(x, y);
  }
  long long res = dfs_1(1, 0, 0);
  dfs_2(1, 0, res);
  printf("%lld\n", result);
  return 0;
}
