#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int N = 200005;
vector<int> a[N];
ll value[N], dp[N], ans, sum[N];
void calc(int u, int p) {
  for (int v : a[u]) {
    if (v == p) continue;
    calc(v, u);
    dp[u] += dp[v] + sum[v];
    sum[u] += sum[v] + value[v];
    dp[u] += value[v];
  }
}
void dfs(int u, int p, ll cur, ll curSum) {
  ans = max(ans, dp[u] + cur);
  curSum += sum[u] + value[u];
  for (int v : a[u]) {
    if (v == p) continue;
    cur += dp[v] + sum[v] + value[v];
  }
  for (int v : a[u]) {
    if (v == p) continue;
    cur -= (dp[v] + sum[v] + value[v]);
    curSum -= sum[v];
    curSum -= value[v];
    dfs(v, u, cur + curSum, curSum);
    cur += (dp[v] + sum[v] + value[v]);
    curSum += sum[v];
    curSum += value[v];
  }
}
int main() {
  int n;
  cin >> n;
  for (int i = 1; i <= n; ++i) {
    cin >> value[i];
  }
  for (int i = 1; i <= n - 1; ++i) {
    int u, v;
    cin >> u >> v;
    a[u].push_back(v);
    a[v].push_back(u);
  }
  calc(1, 1);
  dfs(1, 1, 0, 0);
  cout << ans << "\n";
}
