#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 10;
vector<int> h[N];
long long w[N], down[N], up[N], sum_down[N], sum_up[N];
void dfs_down(int u, int fa) {
  down[u] = sum_down[u] = w[u];
  for (int i = 0; i < h[u].size(); i++) {
    int j = h[u][i];
    if (j == fa) continue;
    dfs_down(j, u);
    sum_down[u] += sum_down[j];
    down[u] += down[j] + sum_down[j];
  }
}
void dfs_up(int u, int fa) {
  for (int i = 0; i < h[u].size(); i++) {
    int j = h[u][i];
    if (j == fa) continue;
    sum_up[j] = sum_down[u] - sum_down[j] + sum_up[u];
    up[j] = up[u] + down[u] - down[j] + sum_up[j] - sum_down[j];
    dfs_up(j, u);
  }
}
int main() {
  int n;
  cin >> n;
  for (int i = 1; i <= n; i++) cin >> w[i];
  for (int i = 1; i <= n - 1; i++) {
    int a, b;
    cin >> a >> b;
    h[a].push_back(b);
    h[b].push_back(a);
  }
  dfs_down(1, -1);
  dfs_up(1, -1);
  long long res = 0;
  for (int i = 1; i <= n; i++) res = max(res, up[i] + down[i]);
  printf("%lld", res - sum_down[1]);
  return 0;
}
