#include <bits/stdc++.h>
using namespace std;
const int mod = 1e9 + 7;
long long n, a[200010], x, y;
pair<long long, long long> dp[200010];
vector<int> elist[200010];
void calc_one(int node, int par) {
  dp[node].second = a[node];
  for (int i = 0; i < elist[node].size(); i++) {
    if (elist[node][i] != par) {
      calc_one(elist[node][i], node);
      dp[node].first += dp[elist[node][i]].first + dp[elist[node][i]].second;
      dp[node].second += dp[elist[node][i]].second;
    }
  }
}
void calc_all(int node, int par) {
  dp[node].first +=
      dp[par].first + dp[par].second - dp[node].first - 2 * dp[node].second;
  dp[node].second = dp[par].second;
  for (int i = 0; i < elist[node].size(); i++)
    if (elist[node][i] != par) calc_all(elist[node][i], node);
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  cin >> n;
  for (int i = 1; i <= n; i++) cin >> a[i];
  for (int i = 1; i < n; i++) {
    cin >> x >> y;
    elist[x].push_back(y);
    elist[y].push_back(x);
  }
  calc_one(1, 0);
  for (int i = 0; i < elist[1].size(); i++) calc_all(elist[1][i], 1);
  long long maxi = -1;
  for (int i = 1; i <= n; i++) maxi = max(maxi, dp[i].first);
  cout << maxi;
}
