#include <bits/stdc++.h>
#define ll long long
#define fi first
#define se second
#define sz(x) (int)x.size()
#define ALL(v) v.begin(),v.end()
#define MASK(k) (1LL << (k))
#define BIT(x, i) (((x) >> (i)) & 1)
#define oo (ll)1e18
#define INF (ll)1e9
#define MOD (ll)(1e9 + 7)
using namespace std;
template<class T1, class T2>
bool maximize(T1 &a, T2 b){if(a < b){a = b; return true;} return false;}
template<class T1, class T2>
bool minimize(T1 &a, T2 b){if(a > b){a = b; return true;} return false;}
template<class T1, class T2>
void add(T1 &a, T2 b){a += b; if(a >= MOD) a -= MOD;}
template<class T1, class T2>
void sub(T1 &a, T2 b){a -= b; if(a < 0) a += MOD;}
template<class T>
void cps(T &v){sort(ALL(v)); v.resize(unique(ALL(v)) - v.begin());}
const int MAX = 3e5 + 10;
int N, A, B;
vector<int> adj[MAX];
int calc(int x, int y, int u, int p = -1){
vector<int> ord;
for(int v: adj[u]){
if(v == p || (u == x && v == y) || (u == y && v == x)) continue;
ord.push_back(calc(x, y, v, u));
}
sort(ALL(ord), greater<int>());
int ma = 0;
for(int i = 0; i < sz(ord); i++){
maximize(ma, i + ord[i]);
}
return ma + 1;
}
vector<int> path;
bool dfs(int u, int p = -1){
bool ans = (u == B);
for(int v: adj[u]){
if(v == p) continue;
ans = ans || dfs(v, u);
}
if(ans) path.push_back(u);
return ans;
}
void solve(){
cin >> N >> A >> B;
for(int i = 1; i < N; i++){
int u, v; cin >> u >> v;
adj[u].push_back(v);
adj[v].push_back(u);
}
dfs(A);
int l = 1, r = sz(path) - 1;
while(l < r){
int m = (l + r) >> 1;
int x = path[m], y = path[m - 1];
if(calc(x, y, A) < calc(x, y, B)){
r = m;
}
else{
l = m + 1;
}
}
int ans = max(calc(path[r], path[r - 1], A), calc(path[r], path[r - 1], B));
if(r > 1) minimize(ans, max(calc(path[r - 2], path[r - 1], A), calc(path[r - 2], path[r - 1], B)));
cout << ans - 1 << '\n';
}
int main(){
ios_base::sync_with_stdio(0); cin.tie(0);
// freopen("task.inp","r",stdin);
// freopen("task.out","w",stdout);
solve();
return 0;
}
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
3 ms |
7516 KB |
Output is correct |
2 |
Correct |
4 ms |
7504 KB |
Output is correct |
3 |
Correct |
4 ms |
7512 KB |
Output is correct |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
203 ms |
23380 KB |
Output is correct |
2 |
Correct |
217 ms |
25000 KB |
Output is correct |
3 |
Correct |
221 ms |
26756 KB |
Output is correct |
4 |
Correct |
236 ms |
26100 KB |
Output is correct |
5 |
Correct |
222 ms |
22964 KB |
Output is correct |
6 |
Correct |
240 ms |
23660 KB |
Output is correct |
7 |
Correct |
225 ms |
27244 KB |
Output is correct |