#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 5;
long long n, a[N], subtree[N], total, ans, initCost;
vector<int> g[N];
void costfromRoot(int v, int prnt, int d) {
  initCost += d * a[v];
  subtree[v] += a[v];
  for (int u : g[v])
    if (u != prnt) {
      costfromRoot(u, v, d + 1);
      subtree[v] += subtree[u];
    }
}
void dfs(int v, int prnt, long long res) {
  ans = max(ans, res);
  for (int u : g[v])
    if (u != prnt) {
      dfs(u, v, res + total - 2 * subtree[u]);
    }
}
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];
    total += 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);
  }
  costfromRoot(1, -1, 0);
  dfs(1, -1, initCost);
  cout << ans << "\n";
  return 0;
}
