#include <bits/stdc++.h>
using namespace std;
const int Mod = 1e9 + 7;
const int maxn = 2e5 + 5;
const double eps = 0.00000001;
const int INF = 0x3f3f3f3f;
long long a[maxn], suma[maxn];
vector<int> vec[maxn];
long long dp[2][maxn];
void DFS(int u, int p) {
  suma[u] = a[u];
  for (auto v : vec[u]) {
    if (v == p) continue;
    DFS(v, u);
    suma[u] += suma[v];
    dp[0][u] += dp[0][v] + suma[v];
  }
}
void DFS2(int u, int p, long long total) {
  for (auto v : vec[u]) {
    if (v == p) continue;
    long long rcost = dp[0][u] - dp[0][v] - suma[v];
    long long boun = suma[1] - suma[v];
    dp[1][v] = total + rcost + boun;
    DFS2(v, u, dp[1][v]);
  }
}
int main() {
  int n;
  cin >> n;
  for (int i = 1; i <= n; i++) cin >> a[i];
  for (int i = 1; i < n; i++) {
    int u, v;
    cin >> u >> v;
    vec[u].push_back(v);
    vec[v].push_back(u);
  }
  DFS(1, 1);
  DFS2(1, 1, 0);
  long long ans = 0;
  for (int i = 1; i <= n; i++) ans = max(ans, dp[1][i] + dp[0][i]);
  cout << ans << endl;
  return 0;
}
