#include <bits/stdc++.h>
using namespace std;
#define task "main"
#define F first
#define S second
#define ii pair<int, int>
#define il pair<int, long long>
#define li pair<long long, int>
#define FOR(i, a, b) for(int i = (a); i <= (b); ++i)
#define FOD(i, b, a) for(int i = (b); i >= (a); --i)
template <class T1, class T2>
bool maximize(T1 &a, T2 b){
if (a < b) {a = b; return true;}
return false;
}
template <class T1, class T2>
bool minimize(T1 &a, T2 b){
if (a > b) {a = b; return true;}
return false;
}
template <class T>
void printArr(T container, string separator = " ", string finish = "\n", ostream &out = cout){
for(auto item: container) out << item << separator;
out << finish;
}
const int MAX_N = (int)2e5 + 5;
const int INF = (int)1e9 + 1408;
int nNode;
vector<int> adj[MAX_N];
int sz[MAX_N];
set<int> A, B;
void dfs(int u, int p) {
sz[u] = 1;
for (int v : adj[u]) if (v != p)
dfs(v, u), sz[u] += sz[v];
}
int ans = INF;
void calc(int x, int y, int z) {
minimize(ans, max({x, y, z}) - min({x, y, z}));
}
void magic(int u, int p) {
int best = (nNode - sz[u]) / 2;
auto it = B.upper_bound(best);
if (it != B.end())
calc(sz[u], *it, nNode - sz[u] - *it);
if (it != B.begin()) {
it--;
calc(sz[u], *it, nNode - sz[u] - *it);
}
best += sz[u];
it = A.upper_bound(best);
if (it != A.end())
calc(sz[u], *it - sz[u], nNode - *it);
if (it != A.begin()) {
it--;
calc(sz[u], *it - sz[u], nNode - *it);
}
A.insert(sz[u]);
for (int v : adj[u]) if (v != p)
magic(v, u);
A.erase(A.find(sz[u]));
B.insert(sz[u]);
}
void solve() {
cin >> nNode;
FOR(i, 1, nNode - 1) {
int u, v;
cin >> u >> v;
adj[u].push_back(v);
adj[v].push_back(u);
}
dfs(1, -1);
magic(1, -1);
cout << ans;
}
int32_t main() {
if (fopen(task".inp", "r")) {
freopen(task".inp", "r", stdin);
freopen(task".out", "w", stdout);
}
ios_base::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
bool multitest = 0;
int numTest = 1;
if (multitest) cin >> numTest;
while (numTest--) {
solve();
}
return 0;
}
/* Lak lu theo dieu nhac!!!! */
컴파일 시 표준 에러 (stderr) 메시지
papricice.cpp: In function 'int32_t main()':
papricice.cpp:97:16: warning: ignoring return value of 'FILE* freopen(const char*, const char*, FILE*)' declared with attribute 'warn_unused_result' [-Wunused-result]
97 | freopen(task".inp", "r", stdin);
| ~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~
papricice.cpp:98:16: warning: ignoring return value of 'FILE* freopen(const char*, const char*, FILE*)' declared with attribute 'warn_unused_result' [-Wunused-result]
98 | freopen(task".out", "w", stdout);
| ~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |