#include using namespace std; #define int long long #define ii pair #define app push_back #define all(a) a.begin(), a.end() #define bp __builtin_popcountll #define ll long long #define mp make_pair #define f first #define s second #define Time (double)clock()/CLOCKS_PER_SEC #define debug(x) std::cout << #x << ": " << x << '\n'; const int N = 1007; vector g[N]; int n, a[N]; vector dp[N]; int ad[N]; void dfs(int u, int p) { for (int v : g[u]) { if (v != p) { dfs(v, u); for (auto e : dp[v]) dp[u].app(e); ad[u] += ad[v]; } } sort(all(dp[u])); reverse(all(dp[u])); int cur = a[u], f = -1; for (int i = 0; i < dp[u].size(); ++i) { if (i % 2 == 0 && cur >= dp[u][i]) { vector su = {cur}; for (int j = i; j < dp[u].size(); ++j) su.app(dp[u][j]); dp[u] = su; return; } cur += dp[u][i] * f; f = -f; } if (dp[u].size() % 2 == 0) { dp[u] = {cur}; } else { dp[u].clear(); ad[u] += cur; } } int get(int u) { int f = 1, ans = 0; dp[u].app(ad[u]); for (auto e : dp[u]) { ans += e * f; f = -f; } return ans; } signed main() { #ifdef HOME freopen("input.txt", "r", stdin); #else #define endl '\n' ios_base::sync_with_stdio(0); cin.tie(0); #endif cin >> n; for (int i = 1; i <= n; ++i) cin >> a[i]; for (int i = 0; i < n - 1; ++i) { int u, v; cin >> u >> v; g[u].app(v); g[v].app(u); } dfs(1, 1); cout << get(1) << endl; }