#include <bits/stdc++.h>
using namespace std;
int mpow(int base, int exp);
void ipgraph(int m);
const int mod = 1000000007;
const int N = 3e5, M = N;
vector<int> g[N];
long long a[N], in[N], out[N], dp[N], sum[N], arr[N], pa[N], up[N], upu[N];
long long tot = 0;
void dfs1(int u, int par) {
  sum[u] = arr[u];
  pa[u] = par;
  for (int v : g[u]) {
    if (v == par) continue;
    dfs1(v, u);
    sum[u] += sum[v];
    in[u] += in[v] + sum[v];
  }
}
void dfs3(int u, int par, long long ups) {
  int mx1(-1), mx2(-1);
  up[u] = ups;
  for (int v : g[u]) {
    if (v == par) continue;
    dfs3(v, u, sum[u] - sum[v] + ups);
  }
}
void dfs2(int u, int par) {
  int mx1(-1), mx2(-1);
  for (int v : g[u]) {
    if (v == par) continue;
    int use = mx1;
    if (mx1 == in[v]) use = mx2;
    out[v] = max(out[u] + up[v], in[u] - (in[v] + sum[v]) + up[v] + out[u]);
    dfs2(v, u);
  }
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  int i, n, k, j, u, v;
  cin >> n;
  for (int i = 1; i <= n; i++) {
    cin >> arr[i];
    tot += arr[i];
  }
  for (i = 0; i < n - 1; i++) {
    cin >> u >> v;
    g[u].push_back(v);
    g[v].push_back(u);
  }
  dfs1(1, 0);
  dfs3(1, 0, 0);
  dfs2(1, 0);
  long long mx = 0;
  for (i = 1; 1 < n + 1 ? i < n + 1 : i > n + 1; 1 < n + 1 ? i += 1 : i -= 1) {
    mx = max(mx, out[i] + in[i]);
  }
  cout << mx << endl;
  return 0;
}
