#include <bits/stdc++.h>
using namespace std;
const int N = 200000;
vector<int> ao[N];
int aa[N];
long long cnt[N], sum[N];
void dfs1(int p, int i) {
  long long c = aa[i], s = 0;
  for (int j : ao[i])
    if (j != p) {
      dfs1(i, j);
      c += cnt[j];
      s += sum[j] + cnt[j];
    }
  cnt[i] = c;
  sum[i] = s;
}
void dfs2(int p, int i, long long c_, long long s_) {
  long long c = cnt[i] + c_;
  long long s = sum[i] + s_ + c_;
  sum[i] = s;
  for (int j : ao[i])
    if (j != p) dfs2(i, j, c - cnt[j], s - sum[j] - cnt[j]);
}
int main() {
  int n;
  scanf("%d", &n);
  for (int i = 0; i < n; i++) scanf("%d", &aa[i]);
  for (int h = 0; h < n - 1; h++) {
    int i, j;
    scanf("%d%d", &i, &j);
    i--, j--;
    ao[i].push_back(j);
    ao[j].push_back(i);
  }
  dfs1(-1, 0);
  dfs2(-1, 0, 0, 0);
  long long ans = 0;
  for (int i = 0; i < n; i++) ans = max(ans, sum[i]);
  printf("%lld\n", ans);
  return 0;
}
