#include <bits/stdc++.h>
using namespace std;
const long long sz = 200005;
vector<long long> adj[sz], subtree(sz), a(sz);
long long ans;
long long dfs1(int node, int parent) {
  long long ret = 0;
  subtree[node] = a[node];
  for (auto it : adj[node]) {
    if (it != parent) {
      ret += dfs1(it, node);
      subtree[node] += subtree[it];
    }
  }
  ret += (subtree[node] - a[node]);
  return ret;
}
void dfs2(int node, int parent, long long val) {
  ans = max(ans, val);
  for (auto it : adj[node]) {
    if (it != parent) {
      dfs2(it, node, val + subtree[1] - 2 * subtree[it]);
    }
  }
}
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  ;
  long long n;
  cin >> n;
  for (int i = 1; i <= n; ++i) cin >> a[i];
  for (int i = 0; i < n - 1; ++i) {
    int x, y;
    cin >> x >> y;
    adj[x].push_back(y);
    adj[y].push_back(x);
  }
  ans = dfs1(1, 1);
  dfs2(1, 1, ans);
  cout << ans;
  return 0;
}
