#include <bits/stdc++.h>
using namespace std;
const int N = 200100;
vector<int> g[N];
long long a[N], dp1[N], dp2[N], sz1[N], sz2[N], n;
void dfs(int v, int p) {
  sz1[v] = a[v];
  for (int i = 0; i < g[v].size(); i++) {
    int to = g[v][i];
    if (to == p) continue;
    dfs(to, v);
    sz1[v] += sz1[to];
    dp1[v] += dp1[to] + sz1[to];
  }
}
void dfs2(int v, int p) {
  for (int i = 0; i < g[v].size(); i++) {
    int to = g[v][i];
    if (to == p) continue;
    dp2[to] = dp2[v] + dp1[v] - dp1[to] + sz2[v] + sz1[v] - sz1[to] * 2;
    sz2[to] = sz2[v] + sz1[v] - sz1[to];
    dfs2(to, v);
  }
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  cin >> n;
  for (int i = 1; i <= n; i++) cin >> a[i];
  for (int i = 2; i <= n; i++) {
    int u, v;
    cin >> u >> v;
    g[u].push_back(v);
    g[v].push_back(u);
  }
  dfs(1, 0);
  dfs2(1, 0);
  long long ans = 0;
  for (int i = 1; i <= n; i++) {
    ans = max(ans, dp1[i] + dp2[i]);
  }
  cout << ans;
}
