#include <bits/stdc++.h>
#pragma optimization_level 3
#pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,fast-math,O3")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx")
using namespace std;
const long double PI = 3.14159265358979323846;
const long long MOD = 1e+9 + 7;
const long long INF = LLONG_MAX;
const int INFi = INT_MAX;
const long long N = 2e+5 + 8;
vector<long long> adj[N];
long long vis[N];
long long dx4[] = {0, 1, 0, -1}, dy4[] = {1, 0, -1, 0};
long long test_cases = 1;
mt19937 rnd(chrono::steady_clock::now().time_since_epoch().count());
;
long long n, a[N], u, v, res, ans;
long long dp[N], accum[N];
void dfs(long long v, long long d) {
  vis[v] = 1;
  accum[v] = a[v];
  res += d * a[v];
  for (auto to : adj[v]) {
    if (!vis[to]) {
      dfs(to, d + 1);
      accum[v] += accum[to];
    }
  }
  vis[v] = 0;
}
void dfs2(long long v) {
  ans = max(ans, dp[v]);
  vis[v] = 1;
  for (auto to : adj[v]) {
    if (!vis[to]) {
      accum[v] -= accum[to];
      dp[to] = dp[v] + accum[v] - accum[to];
      accum[to] += accum[v];
      dfs2(to);
      accum[to] -= accum[v];
      accum[v] += accum[to];
    }
  }
}
void MAIN(long long tc) {
  cin >> n;
  for (long long i = (1); i <= n; i++) cin >> a[i];
  for (long long i = (1); i <= n - 1; i++) {
    cin >> u >> v;
    adj[u].push_back(v);
    adj[v].push_back(u);
  }
  dfs(1, 0);
  dp[1] = res;
  dfs2(1);
  cout << ans << " ";
  cout << "\n";
  ;
  ;
}
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  cout << fixed;
  cout << setprecision(10);
  ;
  for (long long i = (1); i <= test_cases; i++) {
    MAIN(i);
  }
}
