#include <bits/stdc++.h>
using namespace std;
struct node {
  int64_t sm, val;
  node() { sm = val = 0; }
  node(const int64_t _sm, const int64_t _val) {
    sm = _sm;
    val = _val;
  }
  void operator+=(const node &other) {
    sm += other.sm;
    val += other.sm + other.val;
  }
};
int n;
int64_t as[200005];
vector<int> adj[200005];
node inf[200005];
node dfs(int st, int pr) {
  for (auto x : adj[st]) {
    if (x == pr) continue;
    inf[st] += dfs(x, st);
  }
  inf[st].sm += as[st];
  return inf[st];
}
int64_t dfs2(int st, int pr) {
  int64_t ans = inf[st].val;
  for (auto x : adj[st]) {
    if (x == pr) continue;
    inf[x].val = inf[st].val + inf[st].sm - inf[x].sm - inf[x].sm;
    inf[x].sm = inf[st].sm;
    ans = max(ans, dfs2(x, st));
  }
  return ans;
}
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) {
    scanf("%lld", &as[i]);
  }
  for (int i = 1; i < n; i++) {
    int a, b;
    scanf("%d%d", &a, &b);
    adj[a].push_back(b);
    adj[b].push_back(a);
  }
  dfs(1, 0);
  printf("%lld\n", dfs2(1, 0));
  return 0;
}
