#include <bits/stdc++.h>
using namespace std;
long long int n, ans;
vector<long long int> adj[200001];
long long int a[200001];
long long int sum_a[200001];
bool visited[200001];
void dfs(long long int s, long long int prof) {
  visited[s] = true;
  sum_a[s] = a[s];
  ans += (a[s] * prof);
  for (auto const &v : adj[s])
    if (!visited[v]) dfs(v, prof + 1), sum_a[s] += sum_a[v];
}
void dfs2(long long int s, long long int father, long long int at) {
  ans = max(ans, at);
  visited[s] = true;
  for (auto const &v : adj[s]) {
    if (!visited[v]) {
      long long int a1 = at, a2 = sum_a[v], a3 = sum_a[s];
      at -= sum_a[v], sum_a[s] -= sum_a[v], at += sum_a[s],
          sum_a[v] += sum_a[s];
      dfs2(v, s, at);
      at = a1, sum_a[v] = a2, sum_a[s] = a3;
    }
  }
}
signed main() {
  cin >> n;
  for (long long int i = 0; i < n; i++) cin >> a[i];
  for (long long int i = 0; i < n - 1; i++) {
    long long int a, b;
    cin >> a >> b;
    a--, b--;
    adj[a].push_back(b);
    adj[b].push_back(a);
  }
  if (n == 1) {
    cout << "0\n";
    return 0;
  }
  dfs(0, 0);
  memset(visited, 0, sizeof(visited));
  dfs2(0, 0, ans);
  cout << ans << endl;
  return 0;
}
