#include <bits/stdc++.h>
using namespace std;
const int MAX_N = 2e5 + 5;
long long res = 0, mx = 0;
long long sub[MAX_N];
int custo[MAX_N];
vector<vector<int> > g(MAX_N);
void dfs(int node, int p = -1, int d = 0) {
  res += 1LL * d * custo[node];
  sub[node] = custo[node];
  for (auto to : g[node]) {
    if (to != p) {
      dfs(to, node, d + 1);
      sub[node] += sub[to];
    }
  }
}
void root(int node, int p = -1) {
  mx = max(mx, res);
  for (auto to : g[node]) {
    if (to != p) {
      long long old_res = res;
      long long old_node = sub[node];
      long long old_to = sub[to];
      res -= sub[to];
      sub[node] -= sub[to];
      res += sub[node];
      sub[to] += sub[node];
      root(to, node);
      res = old_res;
      sub[node] = old_node;
      sub[to] = old_to;
    }
  }
}
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  int n;
  cin >> n;
  for (int i = 0; i < n; i++) cin >> custo[i];
  for (int i = 0; i < n - 1; i++) {
    int st, et;
    cin >> st >> et;
    --st;
    --et;
    g[st].emplace_back(et);
    g[et].emplace_back(st);
  }
  dfs(0);
  root(0);
  cout << mx << '\n';
  return 0;
}
