#include <cstdio>
#include <algorithm>
#include <vector>

const int maxn = 5010;
const int INF = (int)1e9;

int n;
int cnt[maxn];
std::vector <int> gr[maxn];
bool was[maxn];
int size[maxn];
int d[maxn][maxn];

void dfs(int v, int p = -1) {
    was[v] = true;
    size[v] = 1;
    std::vector <int> children;
    for (int i = 0; i < (int)gr[v].size(); i++) {
        int u = gr[v][i];
        if (u == p)
            continue;
        children.push_back(u);
        dfs(u, v);
        size[v] += size[u];
    }
    if (!children.size()) {
        d[v][0] = d[v][1] = 0;
        return;        
    }
    
    int leftSon = children[0];
    int rightSon = ((int)children.size() == 1) ? -1 : children[1];
    for (int newLeftValue = 0; newLeftValue <= size[leftSon]; newLeftValue++)
        for (int newRightValue = 0; newRightValue <= (rightSon == -1 ? 0 : size[rightSon]); newRightValue++) {
            int newValue = newLeftValue + newRightValue;
            int cost = abs(cnt[leftSon] - newLeftValue) + (rightSon == -1 ? 0 : abs(cnt[rightSon] - newRightValue));
            d[v][newValue] = std::min(d[v][newValue], d[leftSon][newLeftValue] + (rightSon == -1 ? 0 : d[rightSon][newRightValue]) + cost);
        }
}

int main() {
    freopen("tree.in", "r", stdin);
    freopen("tree.out", "w", stdout);
    scanf("%d", &n);
    for (int i = 0; i < n; i++)
        scanf("%d", &cnt[i]);
    for (int i = 0; i < n - 1; i++) {
        int v, u;
        scanf("%d%d", &v, &u);
        --v, --u;
        gr[v].push_back(u);
        gr[u].push_back(v);
    }
    for (int i = 0; i < n; i++)
    for (int j = 0; j <= n; j++)
        d[i][j] = INF;
    dfs(0);

    int ans = INF;
    for (int i = 0; i <= n; i++)
        ans = std::min(ans, d[0][i] + abs(cnt[0] - i));
    printf("%d\n", ans);
    return 0;
}                   
