結果
| 問題 |
No.3348 Tree Balance
|
| コンテスト | |
| ユーザー |
|
| 提出日時 | 2025-10-25 15:51:23 |
| 言語 | C++23 (gcc 13.3.0 + boost 1.87.0) |
| 結果 |
AC
|
| 実行時間 | 449 ms / 5,000 ms |
| コード長 | 1,771 bytes |
| コンパイル時間 | 1,126 ms |
| コンパイル使用メモリ | 117,556 KB |
| 実行使用メモリ | 65,208 KB |
| 最終ジャッジ日時 | 2025-11-13 20:52:30 |
| 合計ジャッジ時間 | 5,974 ms |
|
ジャッジサーバーID (参考情報) |
judge1 / judge2 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| other | AC * 25 |
ソースコード
#include <algorithm>
#include <iostream>
#include <set>
#include <vector>
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 <class T> 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<int> w(n);
rep(i, n) cin >> w[i];
vector<vector<int>> 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<ll> 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<ll> {
set<ll> sums;
ll current = sum[i];
ll remain = total - current;
for (auto &c : graph[i]) {
if (c == p) continue;
set<ll> res = f(f, c, i);
{
auto itr = res.lower_bound(current / 2);
if (itr != res.end()) update(remain, *itr);
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;
}