#include <bits/stdc++.h>
using namespace std;
int main() {
  int n;
  cin >> n;
  vector<long long int> dis(n);
  vector<long long int> ans(n);
  vector<bool> vis(n, 0);
  long long int acc = 0;
  for (long int i = 0; i < n; i++) {
    cin >> dis[i];
    acc += dis[i];
  }
  vector<vector<int>> edg(n);
  for (long int i = 0; i < n - 1; i++) {
    int a, b;
    cin >> a >> b;
    a--;
    b--;
    edg[a].push_back(b);
    edg[b].push_back(a);
  }
  vector<vector<int>> p(3);
  p[0].push_back(0);
  p[1].push_back(0);
  p[2].push_back(0);
  vis[0] = 1;
  int i = 0;
  long long int x = 0;
  while (p[0].size() < n) {
    for (long int j = 0; j < edg[p[0][i]].size(); j++) {
      if (!vis[edg[p[0][i]][j]]) {
        p[0].push_back(edg[p[0][i]][j]);
        p[1].push_back(p[0][i]);
        p[2].push_back(p[2][i] + 1);
        x += ((long long int)(p[2][i] + 1)) * (dis[edg[p[0][i]][j]]);
        vis[edg[p[0][i]][j]] = 1;
      }
    }
    i++;
  }
  for (int j = n - 1; j > 0; j--) {
    dis[p[1][j]] += dis[p[0][j]];
  }
  ans[0] = x;
  for (long int i = 0; i < n; i++) {
    if (i == 0) continue;
    ans[p[0][i]] = acc + ans[p[1][i]] - 2 * dis[p[0][i]];
  }
  cout << *max_element(ans.begin(), ans.end());
  return 0;
}
