#include <bits/stdc++.h>
using namespace std;
vector<int> Graph[200005];
int Array[200005];
long long dp[200005], Cost[200005];
void dfs(int root, int parent, int dist) {
  dp[root] = Array[root];
  Cost[1] += dist * 1LL * Array[root];
  for (int i = 0; i < Graph[root].size(); ++i) {
    if (Graph[root][i] != parent) {
      dfs(Graph[root][i], root, dist + 1);
      dp[root] += dp[Graph[root][i]];
    }
  }
}
void Find_Ans(int root, int parent) {
  Cost[root] = Cost[parent] + dp[1] - 2 * dp[root];
  for (int i = 0; i < Graph[root].size(); ++i) {
    if (Graph[root][i] != parent) Find_Ans(Graph[root][i], root);
  }
}
int main() {
  int N, i, u, v;
  scanf("%d", &N);
  for (i = 1; i <= N; ++i) scanf("%d", Array + i);
  for (i = 1; i < N; ++i) {
    scanf("%d%d", &u, &v);
    Graph[u].emplace_back(v);
    Graph[v].emplace_back(u);
  }
  dfs(1, 0, 0);
  for (i = 0; i < Graph[1].size(); ++i) Find_Ans(Graph[1][i], 1);
  long long Ans = 0;
  for (i = 1; i <= N; ++i) Ans = max(Ans, Cost[i]);
  printf("%lld\n", Ans);
  return 0;
}
