#include <bits/stdc++.h>
using namespace std;
const int nx=3e5+5;
int n, a, b, u, v, dp[nx], res=INT_MAX;
vector<pair<int, int>> d[nx];
pair<int, int> pa[nx];
vector<int> cut;
void dfspa(int u, int p)
{
for (auto [v, idx]:d[u]) if (v!=p) pa[v]={u, idx}, dfspa(v, u);
}
void dfs(int u, int p, int c)
{
dp[u]=0;
vector<int> s;
for (auto [v, idx]:d[u]) if (v!=p&&idx!=c) dfs(v, u, c), s.push_back(dp[v]);
sort(s.begin(), s.end());
reverse(s.begin(), s.end());
for (int i=0; i<(int)s.size(); i++) dp[u]=max(dp[u], i+1+s[i]);
}
int cost(int x)
{
dfs(a, a, x);
dfs(b, b, x);
return max(dp[a], dp[b]);
}
int main()
{
cin.tie(NULL)->sync_with_stdio(false);
cin>>n>>a>>b;
for (int i=1; i<n; i++) cin>>u>>v, d[u].push_back({v, i}), d[v].push_back({u, i});
dfspa(a, a);
int tmp=b;
while (tmp!=a) cut.push_back(pa[tmp].second), tmp=pa[tmp].first;
int l=0, r=cut.size()-1;
while (l<r)
{
int md=(l+r)/2;
//cout<<"here "<<cut[md]<<'\n';
res=min(res, cost(cut[md]));
if (dp[b]>dp[a]) r=md;
else l=md+1;
}
cout<<min(res, cost(cut[l]));
}
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
3 ms |
7512 KB |
Output is correct |
2 |
Correct |
3 ms |
7516 KB |
Output is correct |
3 |
Correct |
3 ms |
7516 KB |
Output is correct |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
210 ms |
24148 KB |
Output is correct |
2 |
Correct |
223 ms |
25536 KB |
Output is correct |
3 |
Correct |
220 ms |
26824 KB |
Output is correct |
4 |
Correct |
237 ms |
26292 KB |
Output is correct |
5 |
Correct |
222 ms |
23632 KB |
Output is correct |
6 |
Correct |
216 ms |
24140 KB |
Output is correct |
7 |
Correct |
219 ms |
27156 KB |
Output is correct |