#include <bits/stdc++.h>
using namespace std;
const int MAXN = 2e5 + 25;
#define mid ((l + r) >> 1)
#define tl (node + 1)
#define tr (node + 2 * (mid - l + 1))
const int bad = -1e7;
int comb (int a, int b, int c) {
return abs(2 * a - c) < abs(2 * b - c) ? a : b;
}
struct SegmentTree {
set <int> tree[2 * MAXN];
int arr[MAXN];
void build (int l, int r, int node) {
for (int i = l; i <= r; i++) tree[node].insert(arr[i]);
if (l == r) return;
build(l, mid, tl); build(mid + 1, r, tr);
}
int get (int l, int r, int a, int b, int c, int node) {
if (a > b || l > r) return bad;
if (l > b || r < a) return bad;
if (l >= a && r <= b) {
int ret = bad;
auto t = tree[node].lower_bound(c);
if (t != tree[node].end()) ret = comb(ret, *t, c);
if (t != tree[node].begin()) {
t--;
ret = comb(ret, *t, c);
}
return ret;
}
return comb(get(l, mid, a, b, c, tl), get(mid + 1, r, a, b, c, tr), c);
}
} cur;
vector <int> adj[MAXN];
int sze[MAXN], n, in[MAXN], out[MAXN], t;
set <int> dd[MAXN];
typedef long long ll;
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()) swap(dd[pos], 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;
}
bool check (int x, int y) {
return in[y] < in[x] && in[x] <= out[y];
}
int main () {
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);
for (int i = 2; i <= n; i++) {
cur.arr[in[i]] = sze[i];
}
cur.arr[in[1]] = bad;
cur.build(1, n, 1);
for (int i = 2; i <= n; i++) {
int x = bad;
for (int j = 2; j <= n; j++) {
if (check(i, j) || check(j, i)) continue;
x = comb(x, sze[j], n - sze[i]);
}
mn = min(mn, max({sze[i], x, n - sze[i] - x}) - min({sze[i], x, n - sze[i] - x}));
}
cout << mn << '\n';
}
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
15 ms |
35676 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
15 ms |
35676 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
15 ms |
35676 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |