#include <bits/stdc++.h>
using LL = long long;
using LD = long double;
using namespace std;
using Graph = vector<vector<int>>;
Graph tree;
vector<LL> cost, DP, delta;
vector<bool> visited;
void dfs1(int u) {
  visited[u] = true;
  delta[u] = cost[u];
  for (int v : tree[u]) {
    if (!visited[v]) {
      dfs1(v);
      DP[u] += DP[v] + delta[v];
      delta[u] += delta[v];
    }
  }
}
LL max_cost = 0;
void dfs2(int u) {
  visited[u] = true;
  max_cost = max(max_cost, DP[u]);
  for (int v : tree[u]) {
    if (!visited[v]) {
      DP[v] = DP[u] + delta[0] - 2 * delta[v];
      dfs2(v);
    }
  }
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr);
  int n;
  cin >> n;
  cost.resize(n);
  for (auto& c : cost) cin >> c;
  tree.resize(n);
  for (auto _ = decltype(n - 1){0}; _ < (n - 1); ++_) {
    int u, v;
    cin >> u >> v;
    u--, v--;
    tree[u].push_back(v);
    tree[v].push_back(u);
  }
  DP.resize(n), delta.resize(n), visited.resize(n);
  dfs1(0);
  fill(std::begin(visited), std::end(visited), false);
  dfs2(0);
  cout << max_cost << endl;
}
