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>
using namespace std;
#define ll long long int
#define sz(x) (int)x.size()
#define ff first
#define ss second
const ll N = 300005;
const ll M = 1e9 + 7;
int T, n, a, b, c, d, p[N];
bool tr = 0, tr1 = 0;
vector <int> v[N], v1;
void dfs1(int x){
if(x == 0) return;
v1.push_back(x);
dfs1(p[x]);
}
void dfs(int x, int y){
p[x] = y;
for(auto i : v[x]){
if(i != y) {
dfs(i,x);
}
}
}
int df(int x, int y){
vector <int> v2;
for(auto i : v[x]){
if((i != y) and (min(x,i) != min(c,d) or max(x,i) != max(c,d))){
v2.push_back(df(i,x));
}
}
sort(v2.rbegin(), v2.rend());
int mx = 0;
for(int i = 0; i < sz(v2); i++){
mx = max(mx, v2[i] + i + 1);
}
return mx;
}
int main(){
ios::sync_with_stdio(false); cin.tie(0);
cin >> n >> a >> b;
for(int i = 1; i < n; i++){
int x, y;
cin >> x >> y;
v[x].push_back(y);
v[y].push_back(x);
}
dfs(a,0);
dfs1(b);
reverse(v1.begin(), v1.end());
int l = 0, r = sz(v1)-2, k = 0;
while(l <= r){
int md = (l + r) / 2;
c = v1[md], d = v1[md+1];
if(df(a,0) < df(b,0)){
l = md+1;
k = md;
}
else {
r = md-1;
}
}
c = v1[k], d = v1[k+1];
int mn = max(df(a,0),df(b,0));
if(sz(v1) > 1){
c = v1[k+1], d = v1[k+2];
mn = min(mn,max(df(a,0),df(b,0)));
}
if(sz(v1) > 2){
c = v1[k+2], d = v1[k+3];
mn = min(mn,max(df(a,0),df(b,0)));
}
cout << mn;
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |