#include <bits/stdc++.h>
using namespace std;
template <typename T, typename V>
void bugp(const pair<T, V> &x) {
  cerr << '{' << x.first << ", " << x.second << '}' << endl;
}
template <typename T, typename U, typename V>
void bugpp(const pair<T, pair<U, V> > &x) {
  cerr << '{' << x.first << ", {" << x.second.first << ", " << x.second.second
       << "}}" << endl;
}
template <typename T>
bool maximize(T &x, const T &y) {
  if (x < y) {
    x = y;
    return 1;
  }
  return 0;
}
template <typename T>
bool minimize(T &x, const T &y) {
  if (x > y) {
    x = y;
    return 1;
  }
  return 0;
}
const int N = 200002;
int n, wnode[N], H[N];
long long sumW[N], res[N], total = 0;
vector<int> G[N];
void calc(int u, int par) {
  res[1] += 1LL * H[u] * wnode[u];
  sumW[u] = wnode[u];
  for (const int &v : G[u]) {
    if (v == par) continue;
    H[v] = H[u] + 1;
    calc(v, u);
    sumW[u] += sumW[v];
  }
}
void DFS(int u, int par) {
  for (const int &v : G[u]) {
    if (v == par) continue;
    res[v] = res[u] + total - 2 * sumW[v];
    DFS(v, u);
  }
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cin >> n;
  for (int i = 1, _n = (n); i <= _n; ++i) {
    cin >> wnode[i];
    total += wnode[i];
  }
  for (int i = 1, _n = (n - 1); i <= _n; ++i) {
    int u, v;
    cin >> u >> v;
    G[u].push_back(v);
    G[v].push_back(u);
  }
  calc(1, 1);
  DFS(1, 1);
  cout << *max_element(res + 1, res + n + 1);
  return 0;
}
