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 ll long long
#define fi first
#define se second
#define endl '\n'
#define MASK(i) (1LL << (i))
#define ull unsigned long long
#define ld long double
#define pb push_back
#define all(x) (x).begin() , (x).end()
#define BIT(x , i) ((x >> (i)) & 1)
#define TASK "task"
#define sz(s) (int) (s).size()
using namespace std;
const int mxN = 5e5 + 227;
const int inf = 1e9 + 277;
const int mod = 1e9 + 7;
const ll infll = 1e18 + 7;
const int base = 307;
const int LOG = 20;
template <typename T1, typename T2> bool minimize(T1 &a, T2 b) {
if (a > b) {a = b; return true;} return false;
}
template <typename T1, typename T2> bool maximize(T1 &a, T2 b) {
if (a < b) {a = b; return true;} return false;
}
int n;
int sub[mxN];
vector<int> adj[mxN];
multiset<int> ms1;
multiset<int> ms2;
int res = inf;
void dfs_pre(int u, int p)
{
sub[u] = 1;
for(int v : adj[u]) {
if(v == p) continue;
dfs_pre(v, u);
sub[u] += sub[v];
}
}
void dfs(int u, int p)
{
if(sz(ms1) > 0) {
for(int d = -1; d <= 1; d++) {
int x = (sub[u] + n + d) / 2;
auto it = ms1.lower_bound(x);
if(it != ms1.end()) {
minimize(res, max({sub[u], *it - sub[u], n - *it}) - min({sub[u], *it - sub[u], n - *it}));
}
if(it != ms1.begin()) {
--it;
minimize(res, max({sub[u], *it - sub[u], n - *it}) - min({sub[u], *it - sub[u], n - *it}));
}
}
}
if(sz(ms2) > 0) {
for(int d = -1; d <= 1; d++) {
int x = (n - sub[u] + d) / 2;
auto it = ms2.lower_bound(x);
if(it != ms2.end()) {
minimize(res, max({sub[u], *it , n - *it - sub[u]}) - min({sub[u], *it, n - *it - sub[u]}));
}
if(it != ms2.begin()) {
--it;
minimize(res, max({sub[u], *it , n - *it - sub[u]}) - min({sub[u], *it, n - *it - sub[u]}));
}
}
}
ms1.insert(sub[u]);
for(int v : adj[u]) {
if(v == p) continue;
dfs(v, u);
}
ms1.erase(ms1.find(sub[u]));
ms2.insert(sub[u]);
}
void solve()
{
cin >> n;
for(int i = 1; i < n; i++) {
int u, v;
cin >> u >> v;
adj[u].pb(v);
adj[v].pb(u);
}
dfs_pre(1, -1);
dfs(1, -1);
cout << res;
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
int tc = 1;
//cin >> tc;
while(tc--) {
solve();
}
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... |