#include <bits/stdc++.h>
using namespace std;
int n;
long long a[200001];
long long son[200001], ans[200001];
vector<int> g[200001];
int dis[200001];
long long sum = 0;
void dfs(int cur, int d) {
  dis[cur] = d;
  son[cur] = a[cur];
  for (const auto nxt : g[cur]) {
    if (dis[nxt] < 0) {
      dfs(nxt, d + 1);
      son[cur] += son[nxt];
    }
  }
}
void calcu(int cur) {
  for (const auto &nxt : g[cur]) {
    if (!dis[nxt]) {
      dis[nxt] = 1;
      ans[nxt] = ans[cur] + sum - 2 * son[nxt];
      calcu(nxt);
    }
  }
}
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  memset(dis, -1, sizeof(dis));
  cin >> n;
  int u, v;
  for (long long i = (1); i < (n + 1); ++i) {
    cin >> a[i];
    sum += a[i];
  }
  for (long long i = (0); i < (n - 1); ++i) {
    cin >> u >> v;
    g[u].push_back(v);
    g[v].push_back(u);
  }
  dfs(1, 0);
  ans[1] = 0;
  for (long long i = (1); i < (n + 1); ++i) ans[1] += a[i] * dis[i];
  memset(dis, 0, sizeof(dis));
  dis[1] = 1;
  calcu(1);
  long long as = 0;
  for (long long i = (1); i < (n + 1); ++i) as = max(as, ans[i]);
  cout << as << endl;
  return 0;
}
