import java.util.*;

public class Main {

    static long[] subtree;
    static int[] b;

    static void DFS(int node, int parent, List<Integer>[] G) {

        subtree[node] = b[node];

        for (int child : G[node]) {

            if (child == parent) {
                continue;
            }

            DFS(child, node, G);

            subtree[node] += subtree[child];
        }
    }

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        int n = scanner.nextInt();

        b = new int[n + 1];
        subtree = new long[n + 1];

        for (int i = 1; i <= n; i++) {
            b[i] = scanner.nextInt();
        }

        List<Integer>[] G = new List[n + 1];

        for (int i = 1; i <= n; i++) {
            G[i] = new ArrayList<>();
        }

        for (int i = 0; i < n - 1; i++) {

            int u = scanner.nextInt();
            int v = scanner.nextInt();

            G[u].add(v);
            G[v].add(u);
        }

        // Root tree at 1
        DFS(1, 0, G);

        long total = subtree[1];

        long answer = Long.MAX_VALUE;

        // Cut the edge parent[i] -- i
        // i.e. consider every non-root node
        // visualise nodes and understand .. node[1] is total sum 
        // node 2 will have only subtree[2] sum and none of node[1](root) and its
        // other child subtree's sum
        for (int i = 2; i <= n; i++) {

            long part1 = subtree[i];
            long part2 = total - subtree[i];

            long difference = Math.abs(part1 - part2);

            answer = Math.min(answer, difference);
        }

        System.out.println(answer);
    }
}