#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 10;
vector<int> G[maxn];
long long sz[maxn], sum, n, sum_val, A[maxn];
void dfs(int u, int fa, int dep) {
  sum += dep * A[u];
  sum_val += A[u];
  sz[u] = A[u];
  for (int i = 0; i < G[u].size(); i++) {
    int v = G[u][i];
    if (v == fa) continue;
    dfs(v, u, dep + 1);
    sz[u] += sz[v];
  }
}
long long ans;
void solve(int u, int fa, long long sum) {
  ans = max(ans, sum);
  for (int i = 0; i < G[u].size(); i++) {
    int v = G[u][i];
    if (v == fa) continue;
    long long Sum = sum - sz[v] + sum_val - sz[v];
    solve(v, u, Sum);
  }
}
int main() {
  scanf("%lld", &n);
  for (int i = 1; i <= n; i++) scanf("%lld", &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, 0, 0);
  solve(1, 0, sum);
  printf("%lld", ans);
  return 0;
}
