#include <bits/stdc++.h>
using namespace std;
long long sum[200005];
long long res = 0;
long long ans = 0;
long long a[200005];
vector<int> g[200005];
void dfs(int v, int p = -1, int h = 0) {
  res += 1ll * h * a[v];
  sum[v] = a[v];
  for (auto i : g[v]) {
    if (p == i) continue;
    dfs(i, v, h + 1);
    sum[v] += sum[i];
  }
}
void dfs2(int v, int p = -1) {
  ans = max(ans, res);
  for (auto i : g[v]) {
    if (p == i) continue;
    res -= sum[i];
    sum[v] -= sum[i];
    res += sum[v];
    sum[i] += sum[v];
    dfs2(i, v);
    res -= sum[v];
    sum[i] -= sum[v];
    sum[v] += sum[i];
    res += sum[i];
  }
}
int main() {
  ios_base::sync_with_stdio(false);
  int n;
  cin >> n;
  for (int i = 0; i < n; i++) cin >> a[i];
  for (int i = 0; i < n - 1; i++) {
    int x, y;
    cin >> x >> y;
    x--, y--;
    g[x].push_back(y);
    g[y].push_back(x);
  }
  dfs(0);
  dfs2(0);
  cout << ans;
}
