#include <bits/stdc++.h>
using namespace std;
const int MAXN = 2 * 100 * 1000 + 17;
int n, a[MAXN], par[MAXN];
long long sum_down[MAXN], sum_up[MAXN], ans[MAXN];
vector<int> adj[MAXN];
long long dfs(int v, int d) {
  long long res = 0;
  for (auto i : adj[v])
    if (i != par[v]) {
      par[i] = v;
      res += dfs(i, d + 1);
    }
  return res + 1LL * d * a[v];
}
void dfs_down(int v) {
  for (auto i : adj[v])
    if (i != par[v]) {
      dfs_down(i);
      sum_down[v] += sum_down[i];
    }
}
void dfs_up(int v) {
  if (v != 1) sum_up[v] = sum_up[par[v]] + sum_down[par[v]] - sum_down[v];
  for (auto i : adj[v])
    if (i != par[v]) dfs_up(i);
}
void dfs_ans(int v) {
  if (v != 1) ans[v] = ans[par[v]] - sum_down[v] + sum_up[v];
  for (auto i : adj[v])
    if (i != par[v]) dfs_ans(i);
}
int main() {
  ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0);
  cin >> n;
  for (int i = 1; i <= n; i++) cin >> a[i], sum_down[i] = a[i];
  for (int i = 1; i < n; i++) {
    int v, u;
    cin >> v >> u;
    adj[v].push_back(u);
    adj[u].push_back(v);
  }
  ans[1] = dfs(1, 0);
  dfs_down(1);
  dfs_up(1);
  dfs_ans(1);
  cout << *max_element(ans + 1, ans + n + 1) << endl;
  return 0;
}
