#include <bits/stdc++.h>
const int maxn = 2e5 + 50;
using namespace std;
int n;
long long a[maxn], dp[maxn], he[maxn];
vector<int> maps[maxn];
void dfs(int u, int fa) {
  he[u] = 0;
  for (int i = 0, len = maps[u].size(); i < len; i++) {
    int v = maps[u][i];
    if (v != fa) {
      dfs(v, u);
      dp[u] += dp[v] + he[v];
      he[u] += he[v];
    }
  }
  he[u] += a[u];
}
long long ans;
void dfs1(int u, int fa) {
  for (int i = 0, len = maps[u].size(); i < len; i++) {
    int v = maps[u][i];
    if (v != fa) {
      dp[v] = dp[u] - he[v] + he[1] - he[v];
      ans = max(ans, dp[v]);
      dfs1(v, u);
    }
  }
}
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
  for (int i = 1, a, b; i < n; i++) {
    scanf("%d%d", &a, &b);
    maps[a].push_back(b);
    maps[b].push_back(a);
  }
  dfs(1, 1);
  ans = dp[1];
  dfs1(1, 1);
  printf("%lld\n", ans);
  return 0;
}
