#include <bits/stdc++.h>
using namespace std;
const int MAXN = 200005;
long long sumInSubtree[MAXN];
long long dp1[MAXN];
long long dp2[MAXN];
long long a[MAXN];
int pa[MAXN];
vector<int> g[MAXN];
void dfs(int u, int p) {
  sumInSubtree[u] = a[u];
  pa[u] = p;
  for (auto v : g[u]) {
    if (v != p) {
      dfs(v, u);
      dp1[u] += dp1[v] + sumInSubtree[v];
      sumInSubtree[u] += sumInSubtree[v];
    }
  }
}
void dfs2(int u, int p) {
  long long contributionFromOutside = dp2[p] + dp1[p];
  if (p) {
    contributionFromOutside -= (dp1[u] + sumInSubtree[u]);
  }
  long long sumOutside = sumInSubtree[1] - sumInSubtree[u];
  dp2[u] = contributionFromOutside + sumOutside;
  for (auto v : g[u]) {
    if (v != p) {
      dfs2(v, u);
    }
  }
}
int main() {
  std::ios::sync_with_stdio(false);
  cin.tie(0);
  int n;
  cin >> n;
  for (int i = 1; i <= n; ++i) {
    cin >> a[i];
  }
  for (int i = 2; i <= n; ++i) {
    int u, v;
    cin >> u >> v;
    g[u].push_back(v);
    g[v].push_back(u);
  }
  dfs(1, 0);
  dfs2(1, 0);
  long long ans = 0;
  for (int i = 1; i <= n; ++i) {
    ans = max(ans, dp1[i] + dp2[i]);
  }
  cout << ans;
}
