This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
using namespace std;
#pragma GCC optimize ("Ofast")
const int MAXN = 2e5 + 25;
const int bad = -1e7;
inline int comb (int a, int b, int c) {
return abs(2 * a - c) < abs(2 * b - c) ? a : b;
}
vector <int> adj[MAXN];
int sze[MAXN], n, in[MAXN], out[MAXN], t;
set <int> dd[MAXN];
int mn = 1e9;
void dfs (int pos, int par) {
sze[pos] = 1;
in[pos] = ++t;
int mx = bad;
for (auto j : adj[pos]) {
if (j == par) continue;
dfs(j, pos);
sze[pos] += sze[j];
if (dd[pos].size() < dd[j].size()) dd[pos].swap(dd[j]);
for (auto i : dd[j]) dd[pos].insert(i);
dd[j].clear();
}
for (auto i : dd[pos]) mx = comb(i, mx, sze[pos]);
dd[pos].insert(sze[pos]);
if (sze[pos] != 1 && pos != 1) mn = min(mn, max({n - sze[pos], sze[pos] - mx, mx}) - min({n - sze[pos], sze[pos] - mx, mx}));
out[pos] = t;
}
set <int> x;
void dfs2 (int pos, int par) {
if (pos != 1 && !x.empty()) {
auto t = x.lower_bound((n - sze[pos]) / 2);
int ret = bad;
if (t != x.end()) ret = *t;
if (t != x.begin()) {
t--;
ret = comb(ret, *t, n - sze[pos]);
}
mn = min(mn, max({sze[pos], ret, n - sze[pos] - ret}) - min({sze[pos], ret, n - sze[pos] - ret}));
}
for (auto j : adj[pos]) if (j != par) dfs2(j, pos);
x.insert(sze[pos]);
}
bool check (int x, int y) {
return in[x] <= in[y] && in[y] <= out[x];
}
int main () {
ios::sync_with_stdio(0);
cin.tie(0);
cin >> n;
for (int i = 1; i < n; i++) {
int a, b;
cin >> a >> b;
adj[a].push_back(b);
adj[b].push_back(a);
}
dfs(1, -1);
dfs2(1, -1);
cout << mn << '\n';
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |