#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 5;
long long w[maxn];
long long s[maxn];
vector<int> e[maxn];
long long dp[maxn];
long long sum, ans;
void dfs1(int u, int fa) {
  s[u] = w[u];
  for (int i = 0; i < e[u].size(); i++) {
    int v = e[u][i];
    if (v == fa) continue;
    dfs1(v, u);
    s[u] += s[v];
    dp[u] = dp[u] + dp[v] + s[v];
  }
}
void dfs2(int u, int fa) {
  if (fa) dp[u] = dp[fa] + sum - 2 * s[u];
  for (int i = 0; i < e[u].size(); i++) {
    int v = e[u][i];
    if (v == fa) continue;
    dfs2(v, u);
  }
  ans = max(ans, dp[u]);
}
int main() {
  int n;
  cin >> n;
  for (int i = 1; i <= n; i++) {
    cin >> w[i];
    sum += w[i];
  }
  for (int i = 1; i < n; i++) {
    int u, v;
    cin >> u >> v;
    e[u].push_back(v);
    e[v].push_back(u);
  }
  dfs1(1, 0);
  dfs2(1, 0);
  cout << ans << endl;
  return 0;
}
