#include <bits/stdc++.h>
using namespace std;
int const MAXn = 2e5 + 2;
long long arr[MAXn];
vector<int> adya[MAXn];
long long subtree[MAXn];
long long distm, best, n;
void DFS(int v, int p, int llev) {
  subtree[v] = 1;
  distm += llev * arr[v];
  for (auto to : adya[v]) {
    if (to == p) continue;
    DFS(to, v, llev + 1);
    subtree[v] += subtree[to];
    arr[v] += arr[to];
  }
}
void sol(int nod, int p, long long dist) {
  best = (best > dist ? best : dist);
  for (auto to : adya[nod]) {
    if (to == p) continue;
    sol(to, nod, dist + arr[1] - (2 * arr[to]));
  }
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  cin >> n;
  for (int i = 1; i <= n; i++) cin >> arr[i];
  for (int i = 1; i < n; i++) {
    int n1, n2;
    cin >> n1 >> n2;
    adya[n1].push_back(n2);
    adya[n2].push_back(n1);
  }
  DFS(1, -1, 0);
  sol(1, -1, distm);
  cout << best;
  return 0;
}
