#include <bits/stdc++.h>
using namespace std ;
const int MAX = 3e5 + 10 ;
int dep[MAX] , P[MAX] , sz[MAX] ;
int n , a , b ;
vector< vector<int> >adj(MAX) ;
void dfs1(int node , int par)
{
P[node] = par ;
for(auto &child : adj[node])
{
if(child == par)
continue ;
dep[child] = dep[node] + 1 ;
dfs1(child , node) ;
}
return ;
}
int x , y ;
int dfs2(int node , int par)
{
vector<int>v ;
for(auto &child : adj[node])
{
if(child == par)
continue ;
if((child == x && y == node) || (child == y && node == x))
continue ;
v.push_back(dfs2(child , node)) ;
}
sort(v.rbegin() , v.rend()) ;
int cnt = 0 ;
for(int i = 0 ; i < v.size() ; ++i)
cnt = max(cnt , v[i]+1+i) ;
return cnt ;
}
int check(int mid , bool flag)
{
int now = b ;
while(dep[now] != mid)
now = P[now] ;
x = P[now] , y = now ;
if(!flag)
return (dfs2(a,-1) <= dfs2(b,-1)) ;
else
return max(dfs2(a , -1) , dfs2(b , -1)) ;
}
int main()
{
ios_base::sync_with_stdio(0) ;
cin.tie(0) ;
cin>>n>>a>>b ;
for(int i = 0 ; i < n-1 ; ++i)
{
int x , y ;
cin>>x>>y ;
adj[x].push_back(y) ;
adj[y].push_back(x) ;
}
dfs1(a , -1) ;
int l = 1 , r = dep[b] ;
int ans = 0 ;
while(l <= r)
{
int mid = (l + r) >> 1 ;
if(check(mid , 0))
ans = mid , l = mid+1 ;
else
r = mid-1 ;
}
//cout<<ans<<" : "<<check(ans , 1)<<"\n" ;
int ans2 = check(ans , 1) ;
if(ans-1 > 0)
ans2 = min(ans2 , check(ans-1 , 1)) ;
if(ans+1 <= dep[b])
ans2 = min(ans2 , check(ans+1 , 1)) ;
return cout<<ans2<<"\n" , 0 ;
}
Compilation message
torrent.cpp: In function 'int dfs2(int, int)':
torrent.cpp:40:20: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
for(int i = 0 ; i < v.size() ; ++i)
~~^~~~~~~~~~
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
9 ms |
7424 KB |
Output is correct |
2 |
Correct |
9 ms |
7424 KB |
Output is correct |
3 |
Correct |
9 ms |
7424 KB |
Output is correct |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
567 ms |
21368 KB |
Output is correct |
2 |
Correct |
558 ms |
26448 KB |
Output is correct |
3 |
Correct |
526 ms |
27704 KB |
Output is correct |
4 |
Correct |
566 ms |
27248 KB |
Output is correct |
5 |
Correct |
552 ms |
24952 KB |
Output is correct |
6 |
Correct |
505 ms |
25564 KB |
Output is correct |
7 |
Correct |
491 ms |
28232 KB |
Output is correct |