This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#ifdef LOCAL
#include "local.h"
#else
#include <bits/stdc++.h>
#define debug(...)
#define DB(...)
#endif
using namespace std;
using ll = long long;
using ld = long double;
#define all(x) x.begin(), x.end()
#define rall(x) x.rbegin(), x.rend()
#define For(i, l, r) for (int i = (l); i <= (r); ++i)
#define Ford(i, r, l) for (int i = (r); i >= (l); --i)
#define Rep(i, n) For (i, 0, (n) - 1)
#define Repd(i, n) Ford (i, (n) - 1, 0)
#define Fe(...) for (auto __VA_ARGS__)
template <class C> inline int isz(const C& c) { return static_cast<int>(c.size()); }
template <class T> inline bool chmin(T& a, const T& b) { return (a > b) ? a = b, true : false; }
template <class T> inline bool chmax(T& a, const T& b) { return (a < b) ? a = b, true : false; }
const bool __initialization = []() {
cin.tie(nullptr)->sync_with_stdio(false);
#define TASK "empty"
if (fopen(TASK".inp", "r")) {
(void)(!freopen(TASK".inp", "r", stdin));
(void)(!freopen(TASK".out", "w", stdout)); }
cout << setprecision(12) << fixed;
return true;
}();
constexpr ld eps = 1e-9;
constexpr int inf = 1e9;
constexpr ll linf = 1e18;
// =============================================================================
constexpr int maxn = 2e5 + 5;
int n;
vector<int> g[maxn];
int sz[maxn];
void DfsSize(int u, int p) {
sz[u] = 1;
Fe (v : g[u]) {
if (v != p) {
DfsSize(v, u);
sz[u] += sz[v];
}
}
}
multiset<int> in, out;
vector<int> findClosest(const multiset<int>& st, int val) {
vector<int> ret;
auto it = st.upper_bound(val);
if (it != st.end()) {
ret.push_back(*it);
}
if (it != st.begin()) {
ret.push_back(*(--it));
}
return ret;
}
int findDiff(int a, int b, int c) {
array<int, 3> temp = { a, b, c };
sort(all(temp));
return temp[2] - temp[0];
}
int Dfs(int u, int p) {
int ret = inf;
vector<int> closest;
{
closest = findClosest(in, (n + sz[u]) / 2);
Fe (vsz : closest) {
chmin(ret, findDiff(sz[u], vsz - sz[u], n - vsz));
}
}
{
closest = findClosest(out, (n - sz[u]) / 2);
Fe (vsz : closest) {
chmin(ret, findDiff(sz[u], vsz, n - sz[u] - vsz));
}
}
in.insert(sz[u]);
Fe (v : g[u]) {
if (v != p) {
chmin(ret, Dfs(v, u));
}
}
in.erase(in.find(sz[u]));
out.insert(sz[u]);
return ret;
}
signed main() {
cin >> n;
For (i, 1, n - 1) {
int u, v; cin >> u >> v;
g[u].push_back(v);
g[v].push_back(u);
}
DfsSize(1, -1);
cout << Dfs(1, -1) << '\n';
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |