#include <bits/stdc++.h>
using namespace std;
inline int read() {
  int x = 0, o = 1;
  char ch = getchar();
  while (ch != '-' && (ch < '0' || ch > '9')) ch = getchar();
  if (ch == '-') o = -1, ch = getchar();
  while (ch >= '0' && ch <= '9') x = x * 10 + ch - '0', ch = getchar();
  return x * o;
}
const int N = 2e5 + 5;
int n, a[N], size[N];
long long ans, cost[N], f[N];
int tot, head[N], nxt[N << 1], to[N << 1];
inline void add(int a, int b) {
  nxt[++tot] = head[a];
  head[a] = tot;
  to[tot] = b;
}
inline void pre_dfs(int u, int fa) {
  size[u] = 1;
  cost[u] = a[u];
  for (int i = head[u]; i; i = nxt[i]) {
    int v = to[i];
    if (v == fa) continue;
    pre_dfs(v, u);
    size[u] += size[v];
    cost[u] += cost[v];
  }
}
inline void dfs(int u, int fa) {
  if (size[u] == 1) return;
  for (int i = head[u]; i; i = nxt[i]) {
    int v = to[i];
    if (v == fa) continue;
    dfs(v, u);
    f[u] += f[v] + cost[v];
  }
}
inline void dp(int u, int fa) {
  for (int i = head[u]; i; i = nxt[i]) {
    int v = to[i];
    if (v == fa) continue;
    f[v] = f[u] - cost[v] + cost[1] - cost[v];
    ans = max(ans, f[v]);
    dp(v, u);
  }
}
int main() {
  n = read();
  for (int i = 1; i <= n; ++i) a[i] = read();
  for (int i = 1; i < n; ++i) {
    int a = read(), b = read();
    add(a, b);
    add(b, a);
  }
  pre_dfs(1, 0);
  dfs(1, 0);
  ans = f[1];
  dp(1, 0);
  printf("%lld\n", ans);
  return 0;
}
