結果
| 問題 |
No.3348 Tree Balance
|
| コンテスト | |
| ユーザー |
|
| 提出日時 | 2025-10-29 15:21:35 |
| 言語 | C++23 (gcc 13.3.0 + boost 1.87.0) |
| 結果 |
AC
|
| 実行時間 | 493 ms / 5,000 ms |
| コード長 | 1,850 bytes |
| コンパイル時間 | 1,159 ms |
| コンパイル使用メモリ | 117,340 KB |
| 実行使用メモリ | 106,720 KB |
| 最終ジャッジ日時 | 2025-11-13 21:03:40 |
| 合計ジャッジ時間 | 6,419 ms |
|
ジャッジサーバーID (参考情報) |
judge2 / judge1 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| other | AC * 25 |
ソースコード
// moveではなくポインタで実装した
#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 = new set<ll>();
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;
}