#include <bits/stdc++.h>
using namespace std;
void show_trace() { cout << endl; }
template <typename Start, typename... Rem>
void show_trace(Start S, Rem... R) {
  cout << ' ' << S;
  show_trace(R...);
}
const int INFi = 2139062143;
const long long INF = 1e18;
const int N = 2e5 + 5;
long long ss[N + 5];
long long dp1[N + 5];
long long dp2[N + 5];
long long a[N + 5];
vector<int> Tree[N + 5];
void dfs1(int u, int p) {
  ss[u] = a[u];
  for (auto v : Tree[u]) {
    if (v == p) continue;
    dfs1(v, u);
    ss[u] += ss[v];
    dp1[u] += dp1[v] + ss[v];
  }
}
long long ans = 0;
long long sum = 0;
void dfs2(int u, int p) {
  if (u == 1) {
    for (auto v : Tree[u]) dfs2(v, u);
  } else {
    dp2[u] = dp2[p] - ss[u] + (sum - ss[u]);
    for (auto v : Tree[u]) {
      if (v == p) continue;
      dfs2(v, u);
    }
  }
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  int n;
  cin >> n;
  for (int i = 1; i <= n; i++) {
    cin >> a[i];
    sum += a[i];
  }
  for (int i = 1; i < n; i++) {
    int u, v;
    cin >> u >> v;
    Tree[u].push_back(v);
    Tree[v].push_back(u);
  }
  dfs1(1, 0);
  ans = dp1[1];
  dp2[1] = dp1[1];
  dfs2(1, 0);
  for (int i = 1; i <= n; i++) {
    ans = max(ans, dp2[i]);
  }
  cout << ans << '\n';
}
