#include <bits/stdc++.h>
using namespace std;
#pragma GCC optimize("O3")
const int64_t N = 2 * 100 * 1000;
vector<int64_t> g[N + 2];
int64_t a[N + 2], sum[N + 3], total = 0;
int64_t ans, hoge;
void dfs1(int64_t u, int64_t lev, int64_t p) {
  sum[u] += a[u];
  ans += lev * a[u];
  for (auto v : g[u]) {
    if (v == p) continue;
    dfs1(v, lev + 1, u);
    sum[u] += sum[v];
  }
}
void dfs2(int64_t curr, int64_t par) {
  assert(sum[curr] == total);
  hoge = max(hoge, ans);
  for (auto v : g[curr]) {
    if (v == par) continue;
    int64_t v_sum = sum[v];
    int64_t rem_sum = total - sum[v];
    ans -= v_sum;
    ans += rem_sum;
    sum[curr] = total - sum[v];
    sum[v] = total;
    dfs2(v, curr);
    ans += v_sum;
    ans -= rem_sum;
    sum[v] = v_sum;
    sum[curr] = total;
  }
}
signed main() {
  int64_t n;
  cin >> n;
  total = 0;
  for (int64_t i = 1; i <= n; ++i) {
    cin >> a[i];
    sum[i] = 0;
    total += a[i];
  }
  for (int64_t i = 1, u, v; i < n; ++i) {
    cin >> u >> v;
    g[u].push_back(v);
    g[v].push_back(u);
  }
  ans = 0;
  dfs1(1, 0, -1);
  hoge = ans;
  dfs2(1, -1);
  cout << hoge << "\n";
  return 0;
}
