#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 5;
long long res, sum[N], F[N];
vector<int> adj[N];
bool visited[N];
int n, a[N];
void Input() {
  cin >> n;
  for (int i = 1; i <= n; i++) cin >> a[i];
  for (int i = 1; i <= n - 1; i++) {
    int u, v;
    cin >> u >> v;
    adj[u].push_back(v);
    adj[v].push_back(u);
  }
}
void Root(int u, int d) {
  F[1] += (long long)d * a[u];
  visited[u] = true;
  for (int v : adj[u]) {
    if (visited[v]) continue;
    Root(v, d + 1);
    sum[u] += sum[v];
  }
  sum[u] += a[u];
}
void DFS(int u) {
  visited[u] = true;
  for (int v : adj[u]) {
    if (visited[v]) continue;
    F[v] = F[u] - sum[v] + sum[1] - sum[v];
    res = max(res, F[v]);
    DFS(v);
  }
}
void Solve() {
  Root(1, 0), res = F[1];
  for (int i = 1; i <= n; i++) visited[i] = false;
  DFS(1);
  cout << res << '\n';
}
int main() {
  Input();
  Solve();
  return 0;
}
