#include <bits/stdc++.h>
using namespace std;
const int MAX_N = 2e5 + 5;
int n, a[MAX_N];
vector<int> g[MAX_N];
long long s[MAX_N], f[MAX_N];
void dfs(int u, int p) {
  s[u] = a[u];
  f[u] = 0;
  for (int v : g[u])
    if (v != p) dfs(v, u), s[u] += s[v], f[u] += f[v] + s[v];
}
void dfs2(int u, int p, long long sp, long long fp) {
  s[u] += sp, f[u] += sp + fp;
  for (int v : g[u])
    if (v != p) dfs2(v, u, s[u] - s[v], f[u] - f[v] - s[v]);
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr);
  cin >> n;
  for (int i = 1; i <= n; i++) cin >> a[i];
  for (int i = 0; i < n - 1; i++) {
    int u, v;
    cin >> u >> v;
    g[u].push_back(v);
    g[v].push_back(u);
  }
  dfs(1, 1);
  dfs2(1, 1, 0, 0);
  cout << *max_element(f + 1, f + 1 + n);
  return 0;
}
