/**
* author: wxhtzdy
* created: 30.06.2022 09:34:28
**/
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n, a, b;
cin >> n >> a >> b;
--a; --b;
vector<vector<int>> g(n);
for (int i = 0; i < n - 1; i++) {
int u, v;
cin >> u >> v;
--u; --v;
g[u].push_back(v);
g[v].push_back(u);
}
vector<int> par(n);
function<void(int, int)> Dfs = [&](int v, int pr) {
par[v] = pr;
for (int u : g[v]) {
if (u != pr) {
Dfs(u, v);
}
}
};
Dfs(a, a);
vector<int> path;
int x = b;
while (x != a) {
path.push_back(x);
x = par[x];
}
pair<int, int> f;
vector<int> dp(n);
Dfs = [&](int v, int pr) {
vector<int> ch;
for (int u : g[v]) {
if (u == pr || make_pair(u, v) == f || make_pair(v, u) == f) {
continue;
}
Dfs(u, v);
ch.push_back(u);
}
dp[v] = 0;
sort(ch.begin(), ch.end(), [&](int i, int j) {
return dp[i] > dp[j];
});
for (int i = 0; i < (int) ch.size(); i++) {
dp[v] = max(dp[v], dp[ch[i]] + i + 1);
}
};
auto Solve = [&](int root, int id) {
f = make_pair(path[id], par[path[id]]);
Dfs(root, root);
return dp[root];
};
int sz = (int) path.size();
int low = 0, high = sz - 1;
while (low < high) {
int mid = (low + high) >> 1;
if (Solve(a, mid) <= Solve(b, mid)) {
high = mid;
} else {
low = mid + 1;
}
}
int ans = 1e9;
for (int i = -1; i <= 1; i++) {
if (low + i >= 0 && low + i < sz) {
ans = min(ans, max(Solve(a, low + i), Solve(b, low + i)));
}
}
cout << ans << '\n';
return 0;
}
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
1 ms |
340 KB |
Output is correct |
2 |
Correct |
1 ms |
340 KB |
Output is correct |
3 |
Correct |
1 ms |
340 KB |
Output is correct |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
452 ms |
25808 KB |
Output is correct |
2 |
Correct |
447 ms |
27352 KB |
Output is correct |
3 |
Correct |
449 ms |
28996 KB |
Output is correct |
4 |
Correct |
501 ms |
28460 KB |
Output is correct |
5 |
Correct |
444 ms |
25364 KB |
Output is correct |
6 |
Correct |
413 ms |
26024 KB |
Output is correct |
7 |
Correct |
376 ms |
29424 KB |
Output is correct |