#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 10;
int n;
long long a[N];
vector<int> g[N];
long long fullsum, sum[N], subres[N], par[N];
void dfs(int u, int f) {
  par[u] = f;
  for (int v : g[u])
    if (v != f) {
      dfs(v, u);
      sum[u] += sum[v];
      subres[u] += subres[v] + sum[v];
    }
  sum[u] += a[u];
}
long long ans[N];
void bfs(int s) {
  memset(ans, -1, sizeof ans);
  queue<int> q;
  q.push(s);
  ans[s] = subres[s];
  while (!q.empty()) {
    int u = q.front();
    q.pop();
    for (int v : g[u])
      if (ans[v] == -1) {
        ans[v] = ans[u] + -2 * sum[v] + fullsum;
        q.push(v);
      }
  }
}
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) {
    scanf("%lld", &a[i]);
    fullsum += a[i];
  }
  for (int i = 1; i < n; i++) {
    int u, v;
    scanf("%d %d", &u, &v);
    g[u].push_back(v);
    g[v].push_back(u);
  }
  dfs(1, -1);
  bfs(1);
  long long res = 0;
  for (int i = 1; i <= n; i++) res = max(res, ans[i]);
  printf("%lld", res);
  return 0;
}
