// #pragma GCC target ("avx,avx2,fma")
// #pragma GCC optimize ("Ofast,inline") // O1 - O2 - O3 - Os - Ofast
// #pragma GCC optimize ("unroll-loops")
#include <bits/stdc++.h>
using namespace std;
#define rep(i, a, b) for (int i = (a); i < (b); ++i)
#define per(i, a, b) for (int i = (b - 1); i >= (a); --i)
#define trav(a, x) for (auto &a : x)
#define all(x) x.begin(), x.end()
#define sz(x) x.size()
#define pb push_back
#define debug(x) cout << #x << " = " << x << endl
#define umap unordered_map
#define uset unordered_set
typedef pair<int, int> ii;
typedef pair<int, ii> iii;
typedef vector<int> vi;
typedef vector<ii> vii;
typedef vector<vi> vvi;
typedef long long ll;
typedef pair<ll, ll> pll;
typedef vector<ll> vll;
typedef vector<pll> vpll;
const int INF = 1'000'000'007;
int n, ans = INF, sub_size[200001];
vi graph[200001];
set<int> cur, old;
void pre(int u, int p) {
sub_size[u] = 1;
trav(v, graph[u]) if (v != p) {
pre(v, u);
sub_size[u]+=sub_size[v];
}
}
void dfs(int u, int p) {
if (sz(cur)) {
int p1 = sub_size[u];
auto it = cur.lower_bound((n - sub_size[u]) / 2 + sub_size[u]);
if (it == cur.end()) --it;
rep(i, 0, 2) {
int p2 = *it - sub_size[u], p3 = n - p1 - p2;
int mn = min(p1, min(p2, p3)), mx = max(p1, max(p2, p3));
ans = min(ans, mx - mn);
if (it == cur.begin()) break;
--it;
}
}
if (sz(old)) {
int p1 = sub_size[u];
auto it = old.lower_bound((n - sub_size[u]) / 2);
if (it == old.end()) --it;
rep(i, 0, 2) {
int p2 = *it - sub_size[u], p3 = n - p1 - p2;
int mn = min(p1, min(p2, p3)), mx = max(p1, max(p2, p3));
ans = min(ans, mx - mn);
if (it == old.begin()) break;
--it;
}
}
if (u) cur.insert(sub_size[u]);
trav(v, graph[u]) if (v != p) dfs(v, u);
cur.erase(sub_size[u]);
old.insert(sub_size[u]);
}
int main() {
cin.tie(0)->sync_with_stdio(0);
cin.exceptions(cin.failbit);
cin >> n;
rep(i, 1, n) {
int u, v;
cin >> u >> v;
graph[--u].pb(--v);
}
pre(0, 0);
dfs(0, 0);
cout << ans << endl;
return 0;
}
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
4 ms |
4940 KB |
Output is correct |
2 |
Correct |
2 ms |
4940 KB |
Output is correct |
3 |
Incorrect |
2 ms |
4940 KB |
Output isn't correct |
4 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
4 ms |
4940 KB |
Output is correct |
2 |
Correct |
2 ms |
4940 KB |
Output is correct |
3 |
Incorrect |
2 ms |
4940 KB |
Output isn't correct |
4 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
4 ms |
4940 KB |
Output is correct |
2 |
Correct |
2 ms |
4940 KB |
Output is correct |
3 |
Incorrect |
2 ms |
4940 KB |
Output isn't correct |
4 |
Halted |
0 ms |
0 KB |
- |