이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define all(x) (x).begin(), (x).end()
#define pii pair<int, int>
#define fi first
#define se second
#define sz(x) (int) (x).size()
const int N = 200000;
int n, ans = (int) 1e9;
vector<int> g[N];
int cnt[N];
multiset<int> a, b;
void get_sz(int v, int pr) {
cnt[v] = 1;
for (auto x : g[v]) {
if (x != pr) {
get_sz(x, v);
cnt[v] += cnt[x];
}
}
}
void solve(int v, int pr = -1) {
{
int X = n - cnt[v];
auto it = b.lower_bound(X / 2);
if (it != b.end()) {
ans = min(ans, max({cnt[v], *it, X - *it}) - min({cnt[v], *it, X - *it}));
}
if (it != b.begin()) {
it--;
ans = min(ans, max({cnt[v], *it, X - *it}) - min({cnt[v], *it, X - *it}));
}
}
{
int X = n + cnt[v];
auto it = a.lower_bound(X / 2);
if (it != a.end()) {
ans = min(ans, max({cnt[v], *it - cnt[v], n - *it}) - min({cnt[v], *it - cnt[v], n - *it}));
}
if (it != a.begin()) {
it--;
ans = min(ans, max({cnt[v], *it - cnt[v], n - *it}) - min({cnt[v], *it - cnt[v], n - *it}));
}
}
a.insert(cnt[v]);
for (auto x : g[v]) {
if (x != pr) {
solve(x, v);
}
}
a.erase(a.find(cnt[v]));
b.insert(cnt[v]);
}
signed main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> n;
for (int i = 1; i < n; i++) {
int x, y;
cin >> x >> y;
x--, y--;
g[x].push_back(y);
g[y].push_back(x);
}
get_sz(0, -1);
solve(0, -1);
cout << ans;
}
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |