#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 10;
long long sum[N], dp1[N], dp2[N], a[N];
vector<int> g[N];
void dfs1(int u, int p) {
  sum[u] = a[u];
  dp1[u] = 0;
  for (int v : g[u]) {
    if (v == p) continue;
    dfs1(v, u);
    sum[u] += sum[v];
    dp1[u] += dp1[v] + sum[v];
  }
}
void dfs2(int u, int p, long long val, long long sm) {
  dp2[u] = val;
  for (int v : g[u]) {
    if (v == p) continue;
    dfs2(v, u, val + sm + dp1[u] - dp1[v] - sum[v] + sum[u] - sum[v],
         sm + sum[u] - sum[v]);
  }
}
int main() {
  int n;
  cin >> n;
  for (int i = 1; i <= n; i++) cin >> a[i];
  for (int i = 1; i < n; i++) {
    int u, v;
    cin >> u >> v;
    g[u].push_back(v);
    g[v].push_back(u);
  }
  dfs1(1, 0);
  dfs2(1, 0, 0, 0);
  long long ans = 0;
  for (int i = 1; i <= n; i++) ans = max(ans, dp1[i] + dp2[i]);
  cout << ans << endl;
}
