結果

問題 No.3348 Tree Balance
コンテスト
ユーザー abc864197532
提出日時 2025-11-13 21:50:30
言語 C++23
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 450 ms / 5,000 ms
コード長 2,229 bytes
コンパイル時間 3,034 ms
コンパイル使用メモリ 288,512 KB
実行使用メモリ 69,584 KB
最終ジャッジ日時 2025-11-13 21:50:42
合計ジャッジ時間 7,949 ms
ジャッジサーバーID
(参考情報)
judge1 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 25
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
#define all(a) a.begin(), a.end()
#define sz(a) ((int)a.size())
#define pb push_back
#ifdef Doludu
template <typename T>
ostream& operator << (ostream &o, vector<T> vec) {
    o << "{"; int f = 0;
    for (T i : vec) o << (f++ ? " " : "") << i;
    return o << "}";
}
void bug__(int c, auto ...a) {
    cerr << "\e[1;" << c << "m";
    (..., (cerr << a << " "));
    cerr << "\e[0m" << endl;
}
#define bug_(c, x...) bug__(c, __LINE__, "[" + string(#x) + "]", x)
#define bug(x...) bug_(32, x)
#define bugv(x...) bug_(36, vector(x))
#define safe bug_(33, "safe")
#else
#define bug(x...) void(0)
#define bugv(x...) void(0)
#define safe void(0)
#endif
const int mod = 998244353, N = 200087;

int main() {
    ios::sync_with_stdio(false), cin.tie(0);
    int n;
    cin >> n;
    vector <ll> a(n);
    for (int i = 0; i < n; ++i) cin >> a[i];
    vector <vector <int>> adj(n);
    for (int i = 0, u, v; i < n - 1; ++i) {
        cin >> u >> v, --u, --v;
        adj[u].pb(v), adj[v].pb(u);
    }
    ll tot = accumulate(all(a), 0ll);
    ll ans = 1ll << 60;
    auto upd = [&](ll x, ll y) {
        ans = min(ans, max({x, y, tot - x - y}) - min({x, y, tot - x - y}));
    };
    auto dfs = [&](auto self, int v, int pa) -> multiset<ll> {
        multiset <ll> cur;
        for (int u : adj[v]) if (u != pa) {
            auto nxt = self(self, u, v);
            a[v] += a[u];
            if (sz(cur) < sz(nxt)) swap(cur, nxt);
            for (ll i : nxt) {
                auto it = cur.lower_bound((tot - i) / 2);
                if (it != cur.end()) {
                    upd(*it, i);
                }
                if (it != cur.begin()) {
                    upd(*prev(it), i);
                }
            }
            for (ll i : nxt) {
                cur.insert(i);
            }
            nxt.clear();
        }
        auto it = cur.lower_bound(a[v] / 2);
        if (it != cur.end()) {
            upd(*it, a[v] - *it);
        }
        if (it != cur.begin()) {
            upd(*prev(it), a[v] - *prev(it));
        }
        cur.insert(a[v]);
        return cur;
    };
    dfs(dfs, 0, -1);
    cout << ans << "\n";
}
0