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;
using ll = long long;
using pii = pair<int, int>;
using pll = pair<ll, ll>;
#define F first
#define S second
#define eb emplace_back
#define ep emplace
#define mkp make_pair
#define ALL(x) x.begin(), x.end()
#define MEM(x) memset(x, 0, sizeof(x));
#define MEMS(x) memset(x, -1, sizeof(x));
const int INF = 0x3f3f3f3f;
const ll LINF = 0x3f3f3f3f3f3f3f3f;
/*-------------------------------------------------------------------------*/
const ll MOD = 1e9 + 7;
const int N = 2e5 + 5;
int n;
vector<int> G[N];
set<int> stA, stB;
int sz[N];
void dfs(int u, int p = -1) {
sz[u] = 1;
for(auto& v : G[u]) if(v != p) {
dfs(v, u);
sz[u] += sz[v];
}
}
int ans = INF;
void dfs2(int u, int p = -1) {
// Case1: is Ancestor
{
auto it = stA.upper_bound((n + sz[u]) / 2);
if(it != stA.end()) {
// if(u == 7) cout << *it << '\n';
int mx = max({*it - sz[u], sz[u], n - *it});
int mn = min({*it - sz[u], sz[u], n - *it});
ans = min(ans, mx - mn);
}
if(it != stA.begin()) {
auto iit = prev(it);
// if(u == 7) cout << *it << '\n';
int mx = max({*iit - sz[u], sz[u], n - *iit});
int mn = min({*iit - sz[u], sz[u], n - *iit});
ans = min(ans, mx - mn);
}
}
// Case2: Not Ancestor
{
auto it = stB.upper_bound((n - sz[u]) / 2);
if(it != stB.end()) {
int mx = max({*it, sz[u], n - *it - sz[u]});
int mn = min({*it, sz[u], n - *it - sz[u]});
ans = min(ans, mx - mn);
}
if(it != stB.begin()) {
auto iit = prev(it);
int mx = max({*iit, sz[u], n - *iit - sz[u]});
int mn = min({*iit, sz[u], n - *iit - sz[u]});
ans = min(ans, mx - mn);
}
}
stA.ep(sz[u]);
for(auto& v : G[u]) if(v != p) {
dfs2(v, u);
}
stA.erase(sz[u]);
stB.ep(sz[u]);
}
inline void solve() {
cin >> n;
for(int i = 0; i < n - 1; ++i) {
int u, v; cin >> u >> v;
G[u].eb(v);
G[v].eb(u);
}
dfs(1);
dfs2(1);
cout << ans << '\n';
}
signed main() {
cin.tie(nullptr), cout.tie(nullptr), ios::sync_with_stdio(false);
solve();
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |