This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#pragma GCC optimize("unroll-loops,Ofast,O3")
#include <bits/stdc++.h>
#define pb push_back
#define mp make_pair
#define spc << " " <<
#define all(x) x.begin(), x.end()
#define ll long long
#define int long long
#define ii pair<int,int>
#define vi vector<int>
#define vii vector<ii>
#define st first
#define nd second
#define inf 1000000009
#define MOD 998244353
using namespace std;
vi edges[200005];
int sub[200005], par[200005];
int lim;
void subby(int node){
sub[node]=1;
for(auto i:edges[node]){
if(par[node]==i || i==0) continue;
par[i]=node;
subby(i);
sub[node]+=sub[i];
}
}
int dfs(int node){
for(auto i:edges[node]){
if(i==par[node] || i==0) continue;
if(sub[i]>=lim) return dfs(i);
}
return node;
}
void solve(){
int n; cin >> n;
lim = (n-1)/3+1;
for(int i=1; i<n; i++){
int a,b; cin >> a >> b;
edges[a].pb(b);
edges[b].pb(a);
}
par[1]=0;
subby(1);
int root = dfs(1);
int arr[3];
//cerr << root spc sub[root] << endl;
if(root==1){
vi yea;
for(auto i:edges[1]) yea.pb(sub[i]);
sort(all(yea), greater<int>());
//cerr << yea[0] spc yea[1] << endl;
arr[0] = sub[1]-yea[0]-yea[1];
arr[1] = yea[0];
arr[2] = yea[1];
}
else if(sub[root]>=n/2){
arr[0] = sub[1]-sub[root];
lim = (sub[root]-1)/3+1;
int root2 = dfs(root);
arr[1] = sub[root]-sub[root2];
arr[2] = sub[root2];
}
else{
//cerr << "ok" << endl;
arr[0] = sub[root];
for(auto &i:edges[par[root]]){
if(i==root){
i=0;
break;
}
}
subby(1);
//for(int i=1; i<=n; i++) cerr << i spc sub[i] << endl;
lim = (sub[1]-1)/3+1;
root=dfs(1);
arr[1] = sub[1]-sub[root];
arr[2] = sub[root];
}
sort(arr, arr+3);
cout << arr[2]-arr[0] << endl;
}
signed main(){
ios_base::sync_with_stdio(false);cin.tie(0);
#ifdef Local
freopen("in","r",stdin);
freopen("out","w",stdout);
#endif
ll t=1;
//cin >> t;
while(t--) 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... |