#include #include #include #include using namespace std; using ll = long long; #define rep(i, n) for (ll i = 0; i < (ll)(n); i++) #define all(v) begin(v), end(v) template bool chmin(T &dst, T src) { if (dst > src) { dst = src; return true; } return false; } int main() { cin.tie(nullptr); ios::sync_with_stdio(false); int n; cin >> n; vector w(n); rep(i, n) cin >> w[i]; vector> graph(n); rep(i, n - 1) { int a, b; cin >> a >> b; a--; b--; graph[a].emplace_back(b); graph[b].emplace_back(a); } vector sum(all(w)); auto dfs1 = [&](auto &&f, int i, int p) -> ll { for (auto &c : graph[i]) { if (c == p) continue; sum[i] += f(f, c, i); } return sum[i]; }; dfs1(dfs1, 0, -1); ll total = sum[0]; ll ans = 1LL << 60; auto update = [&](ll s1, ll s2) { auto [mn, mx] = minmax({s1, s2, total - s1 - s2}); chmin(ans, mx - mn); }; auto dfs2 = [&](auto &&f, int i, int p) -> set { set sums; ll current = sum[i]; ll remain = total - current; for (auto &c : graph[i]) { if (c == p) continue; set res = f(f, c, i); { auto itr = res.lower_bound(current / 2); if (itr != res.begin()) update(remain, *--itr); } if (sums.size() < res.size()) swap(sums, res); for (auto e : res) { auto itr = sums.lower_bound((total - e) / 2); if (itr != res.end()) update(e, *itr); if (itr != res.begin()) update(e, *--itr); } sums.insert(all(res)); } sums.insert(current); return sums; }; dfs2(dfs2, 0, -1); cout << ans << endl; }