#include <bits/stdc++.h>
using namespace std;
long long i, n, j, m, k, a, b, Max, arr[200001], dp[200001], sum[200001],
    fix[200001];
vector<long long> v[200001];
void dfs(long long t, long long p, long long ans) {
  if (fix[t] == 1) return;
  fix[t] = 1;
  dp[1] += ans * arr[t];
  for (long long j = 0; j < v[t].size(); j++) {
    dfs(v[t][j], t, ans + 1);
  }
  sum[p] += sum[t];
}
void dfs1(long long t, long long p) {
  if (fix[t] == 1) return;
  fix[t] = 1;
  if (t != 1) dp[t] = dp[p] - 2 * sum[t] + sum[1];
  for (long long j = 0; j < v[t].size(); j++) {
    dfs1(v[t][j], t);
  }
}
int main() {
  cin >> n;
  for (i = 1; i <= n; i++) {
    cin >> arr[i];
    sum[i] = arr[i];
  }
  for (i = 1; i < n; i++) {
    cin >> a >> b;
    v[a].push_back(b);
    v[b].push_back(a);
  }
  dfs(1, 0, 0);
  for (i = 1; i <= n; i++) {
    fix[i] = 0;
  }
  dfs1(1, 0);
  for (i = 1; i <= n; i++) {
    Max = max(Max, dp[i]);
  }
  cout << Max << endl;
  return 0;
}
