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>
#define PB push_back
#define sz(x) ((int)x.size())
using namespace std;
const int N = 200100;
const int oo = 2e9;
multiset<int> A, B;
multiset<int>::iterator itr;
vector<int> g[N];
int n, siz[N], ans = oo;
void calc_siz(int v, int p){
siz[v] = 1;
for (int u : g[v]){
if (u == p) continue;
calc_siz(u, v);
siz[v] += siz[u];
}
}
void upd(int x, int y, int z){
ans = min(ans, max(max(abs(x - y), abs(y - z)), abs(z - x)));
}
void dfs(int v, int p){
if (v > 0) {
if (sz(A) > 0){
itr = A.upper_bound((n + siz[v]) / 2);
if (itr != A.end()){
int cur = (*itr);
upd(siz[v], cur - siz[v], n - cur);
}
if (itr != A.begin()){
int cur = (*prev(itr));
upd(siz[v], cur - siz[v], n - cur);
}
}
if (sz(B) > 0){
itr = B.upper_bound((n - siz[v]) / 2);
if (itr != B.end()){
int cur = (*itr);
upd(siz[v], cur, n - cur - siz[v]);
}
if (itr != B.begin()){
int cur = (*prev(itr));
upd(siz[v], cur, n - cur - siz[v]);
}
}
A.insert(siz[v]);
}
for (int u : g[v]){
if (u == p) continue;
dfs(u, v);
}
if (v > 0){
A.erase(A.find(siz[v]));
B.insert(siz[v]);
}
}
int main(){
ios_base::sync_with_stdio(0); cin.tie(0);
#ifdef _LOCAL
freopen("in.txt","r",stdin);
#endif // _LOCAL
cin >> n;
for (int i = 1; i < n; i++){
int x, y; cin >> x >> y; x--; y--;
g[x].PB(y);
g[y].PB(x);
}
calc_siz(0, -1);
dfs(0, -1);
cout << ans;
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |