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>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/rope>
using namespace std;
using namespace __gnu_pbds;
using namespace __gnu_cxx;
#define ll long long
#define ii pair<ll,ll>
#define iii pair<ii,ll>
#define fi first
#define se second
#define endl '\n'
#define debug(x) cout << #x << " is " << x << endl
#define pub push_back
#define pob pop_back
#define puf push_front
#define pof pop_front
#define lb lower_bound
#define up upper_bound
#define rep(x,start,end) for(auto x=(start)-((start)>(end));x!=(end)-((start)>(end));((start)<(end)?x++:x--))
#define all(x) (x).begin(),(x).end()
#define sz(x) (int)(x).size()
#define indexed_set tree<ll,null_type,less<ll>,rb_tree_tag,tree_order_statistics_node_update>
//change less to less_equal for non distinct pbds, but erase will bug
mt19937 rng(chrono::system_clock::now().time_since_epoch().count());
int n;
vector<int> al[200005];
set<int> s[200005];
int sz[200005];
void dfs_sz(int i,int p){
sz[i]=1;
for (auto &it:al[i]){
if (it==p) continue;
dfs_sz(it,i);
sz[i]+=sz[it];
}
}
ll ans=1e9;
ll calc(int i,int j){
int k=n-i-j;
int arr[3]={i,j,k};
sort(arr,arr+3);
return arr[2]-arr[0];
}
void dfs(int i,int p){
for (auto &it:al[i]){
if (it==p) continue;
dfs(it,i);
if (sz(s[it])>sz(s[i])) swap(s[it],s[i]);
for (auto &it:s[it]){
auto temp=s[i].lb((n-it)/2);
if (temp!=s[i].begin()){
ans=min(ans,calc(it,*prev(temp)));
}
if (temp!=s[i].end()){
ans=min(ans,calc(it,*temp));
}
}
s[i].insert(all(s[it]));
// auto temp=s[i];
// for (auto &it:s[it]){
// s[i].insert(it);
// for (auto &it2:temp) ans=min(ans,calc(it,it2));
// }
}
auto temp=s[i].lb(sz[i]/2);
if (temp!=s[i].begin()){
ans=min(ans,calc(sz[i]-*prev(temp),*prev(temp)));
}
if (temp!=s[i].end()){
ans=min(ans,calc(sz[i]-*temp,*temp));
}
//for (auto &it:s[i]) ans=min(ans,calc(sz[i]-it,it));
s[i].insert(sz[i]);
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin.exceptions(ios::badbit | ios::failbit);
cin>>n;
int a,b;
rep(x,1,n){
cin>>a>>b;
al[a].pub(b);
al[b].pub(a);
}
dfs_sz(1,-1);
dfs(1,-1);
cout<<ans<<endl;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |