#include <bits/stdc++.h>
using namespace std;
vector<long long> g[200001];
long long arr[200001];
long long val[200001];
long long sum[200001];
long long tot_sum = 0;
void dfs(long long beta, long long baap) {
  for (long long i = 0; i < g[beta].size(); i++) {
    long long pota = g[beta][i];
    if (pota == baap) continue;
    dfs(pota, beta);
    val[beta] += val[pota];
    sum[beta] += sum[pota] + arr[pota];
  }
  val[beta] += sum[beta];
}
void dfs2(long long beta, long long baap) {
  if (baap != 0) val[beta] = val[baap] - 2 * (sum[beta] + arr[beta]) + tot_sum;
  for (long long i = 0; i < g[beta].size(); i++) {
    long long pota = g[beta][i];
    if (pota == baap) continue;
    dfs2(pota, beta);
  }
}
int main() {
  long long n;
  scanf("%I64d", &n);
  for (long long i = 1; i <= n; i++) {
    scanf("%I64d", &arr[i]);
    tot_sum += arr[i];
  }
  for (long long i = 0; i < n - 1; i++) {
    long long x, y;
    scanf("%lld %lld", &x, &y);
    g[x].push_back(y);
    g[y].push_back(x);
  }
  dfs(1, 0);
  dfs2(1, 0);
  long long maxi = 0;
  for (long long i = 1; i <= n; i++) {
    maxi = max(maxi, val[i]);
  }
  printf("%lld\n", maxi);
  return 0;
}
