#include <bits/stdc++.h>
using namespace std;
long long n, a[200002], v1, v2, ans[200002], mx, subtr[200002];
vector<long long> g[200002];
void dfs(int v, int d, int p) {
  ans[1] += a[v] * d;
  for (int to : g[v]) {
    if (to == p) continue;
    dfs(to, d + 1, v);
  }
}
void dfs2(int v, int p) {
  long long curr = a[v];
  for (int to : g[v]) {
    if (to == p) continue;
    dfs2(to, v);
    curr += subtr[to];
  }
  subtr[v] = curr;
}
void dfs3(int v, int p) {
  for (int to : g[v]) {
    if (to == p) continue;
    ans[to] = ans[v] + subtr[1] - 2 * subtr[to];
    dfs3(to, v);
  }
  mx = max(mx, ans[v]);
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  cin >> n;
  for (int i = 1; i <= n; i++) cin >> a[i];
  for (int i = 1; i <= n - 1; i++) {
    cin >> v1 >> v2;
    g[v1].push_back(v2);
    g[v2].push_back(v1);
  }
  dfs(1, 0, -1);
  dfs2(1, -1);
  dfs3(1, -1);
  cout << mx;
  return 0;
}
