#include <iostream>
#include <vector>
#include <set>
#include <map>
#include <algorithm>
#include <string>
#include <sstream>
#include <fstream>
#include <cmath>
#include <queue>
#include <stack>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#define lcm(a,b) (a/__gcd(a,b))*b
#define fast ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define ll long long int
#define vi vector<int>
#define vll vector<ll>
#define pb push_back
#define F first
#define S second
#define mp make_pair
using namespace std;
const int tam=200005;
vi G[tam];
int sz[tam];
multiset<int> todos,down;
int res=1e9;
void init(int nodo, int ant){
sz[nodo]=1;
for(auto x:G[nodo]){
if(x!=ant){
init(x,nodo);
sz[nodo]+=sz[x];
}
}
}
int n;
//haré un small to large
void dfs(int nodo, int ant){
//primero quiero probar con los de arriba
int grupo1=sz[nodo];
//n-it2, it2-grupo1, grupo1
//quiero elegir el mejor it2 de don tal que, n-it2 sea los mas cercano a it2-grupo1
auto it2=down.lower_bound((n+grupo1)/2);
if(it2!=down.end()){
int val=(*it2);
vi A;
A.pb(val-grupo1);A.pb(grupo1);A.pb(n-val);
sort(A.begin(),A.end());
res=min(res,A[2]-A[0]);
}
it2=down.begin();
if(it2!=down.end()){
int val=(*it2);
vi A;
A.pb(val-grupo1);A.pb(grupo1);A.pb(n-val);
sort(A.begin(),A.end());
res=min(res,A[2]-A[0]);
}
if(ant!=-1){
down.insert(sz[nodo]);
}
//dfs
// cout<<"nodardo "<<nodo<<endl;
for(auto it : G[nodo]){
if(it==ant)continue;
int tami=sz[it];
int falta=n-tami;
auto it2=todos.lower_bound(falta/2);
// if(it==5){
// cout<<"val "<<todos.size()<<endl;
// for(auto x:todos){
// cout<<x<<" ";
// }
// cout<<endl;
// }
if(it2!=todos.end()){
int val=(*it2);
vi A;
A.pb(val);A.pb(falta-val);A.pb(tami);
sort(A.begin(),A.end());
res=min(res,A[2]-A[0]);
}
it2=todos.begin();
if(it2!=todos.end()){
int val=(*it2);
vi A;
A.pb(val);A.pb(falta-val);A.pb(tami);
sort(A.begin(),A.end());
res=min(res,A[2]-A[0]);
}
dfs(it,nodo);
}
// cout<<"nodo "<<nodo<<endl;
if(ant!=-1){
//ya puedo meter
// cout<<"metiendo "<<sz[nodo]<<endl;
todos.insert(sz[nodo]);
down.erase(down.find(sz[nodo]));
}
}
int main(){
int a,b;
cin>>n;
for(int i=1;i<n;i++){
cin>>a>>b;
G[a].pb(b);
G[b].pb(a);
}
init(1,-1);
dfs(1,-1);
cout<<res<<endl;
return 0;
}
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
4 ms |
5076 KB |
Output is correct |
2 |
Correct |
3 ms |
4948 KB |
Output is correct |
3 |
Incorrect |
3 ms |
4944 KB |
Output isn't correct |
4 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
4 ms |
5076 KB |
Output is correct |
2 |
Correct |
3 ms |
4948 KB |
Output is correct |
3 |
Incorrect |
3 ms |
4944 KB |
Output isn't correct |
4 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
4 ms |
5076 KB |
Output is correct |
2 |
Correct |
3 ms |
4948 KB |
Output is correct |
3 |
Incorrect |
3 ms |
4944 KB |
Output isn't correct |
4 |
Halted |
0 ms |
0 KB |
- |