#include <bits/stdc++.h>
using namespace std;
const int inf = 2e9 + 500;
const int N = 2e5 + 1;
const int bits = 20;
const long double pi = 3.14159265358979323846;
const long long mod = 998244353;
const long long p = 29;
int n;
vector<int> adj[N];
long long dp1[N], dp2[N], sub[N], arr[N];
void dfs1(int node, int par = 0) {
  sub[node] = arr[node];
  for (int nxt : adj[node]) {
    if (nxt != par) {
      dfs1(nxt, node);
      sub[node] += sub[nxt];
      dp1[node] += dp1[nxt] + sub[nxt];
    }
  }
}
void dfs2(int node, int par = 0) {
  if (par != 0) {
    dp2[node] = dp2[par] - sub[node] + sub[1] - sub[node];
  }
  for (int nxt : adj[node]) {
    if (nxt != par) {
      dfs2(nxt, node);
    }
  }
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  ;
  std::cout << std::fixed << std::setprecision(20);
  ;
  cin >> n;
  for (int i = 1; i <= n; i++) {
    cin >> arr[i];
  }
  int u, v;
  for (int i = 1; i < n; i++) {
    cin >> u >> v;
    adj[u].push_back(v);
    adj[v].push_back(u);
  }
  dfs1(1);
  dp2[1] = dp1[1];
  dfs2(1);
  long long ans = dp2[1];
  for (int i = 2; i <= n; i++) {
    ans = max(ans, dp2[i]);
  }
  cout << ans << "\n";
}
