#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(false);
  int n;
  cin >> n;
  vector<int> cost(n);
  for (int i = 0; i < n; i++) {
    cin >> cost[i];
  }
  vector<vector<int> > g(n);
  for (int i = 0; i < n - 1; i++) {
    int u, v;
    cin >> u >> v;
    u--;
    v--;
    g[u].push_back(v);
    g[v].push_back(u);
  }
  vector<long long> sum(n), dp_up(n), dp_down(n);
  function<void(int, int)> dfs_down = [&](int u, int pa) {
    sum[u] = cost[u];
    for (auto v : g[u]) {
      if (v == pa) continue;
      dfs_down(v, u);
      sum[u] += sum[v];
      dp_down[u] += dp_down[v] + sum[v];
    }
  };
  function<void(int, int)> dfs_up = [&](int u, int pa) {
    if (pa != -1) {
      dp_up[u] = dp_up[pa] + dp_down[pa];
      dp_up[u] -= dp_down[u] + sum[u];
      dp_up[u] += sum[0] - sum[u];
    }
    for (auto v : g[u]) {
      if (v == pa) continue;
      dfs_up(v, u);
    }
  };
  dfs_down(0, -1);
  dfs_up(0, -1);
  long long ans = 0;
  for (int i = 0; i < n; i++) {
    ans = max(ans, dp_down[i] + dp_up[i]);
  }
  cout << ans << '\n';
  return 0;
}
