#include<bits/stdc++.h>
using namespace std;
const int N = 3e5 + 5;
int n;
vector<int> adj[N];
vector<pair<int, int>> path;
int A, B, trace[N];
void dfs(int u, int p)
{
for(auto v: adj[u])
{
if(v == p) continue;
trace[v] = u;
dfs(v, u);
}
}
int DFS(int u, int p, pair<int, int> block) {
int sum = 0;
vector<int> res;
for(int v : adj[u])
{
if(v == p)
continue;
if(make_pair(u, v) == block || make_pair(v, u) == block)
continue;
res.push_back(DFS(v, u, block));
}
sort(res.begin(), res.end());
reverse(res.begin(), res.end());
for(int i = 0; i < res.size(); i++)
sum = max(sum, res[i] + (i + 1));
return sum;
}
bool Check(int mid)
{
//check coi max cay a > max cay b ko??
pair<int, int> block = path[mid];
return DFS(A, 0, block) > DFS(B, 0, block);
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
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, 0);
int x = B;
while(x != A)
{
path.push_back({trace[x], x});
x = trace[x];
}
reverse(path.begin(), path.end());
// for(auto tmp: path)
// {
// cout << tmp.first << ' ' << tmp.second << endl;
// }
int l = 0, r = path.size() - 1, ans = 0;
while(l <= r)
{
int mid = (l + r) / 2;
if(Check(mid))
{
ans = mid;
r = mid - 1;
}
else
l = mid + 1;
}
int res = max(DFS(A, 0, path[ans]), DFS(B, 0, path[ans]));
res = min(res, max(DFS(A, 0, path[ans - 1]), DFS(B, 0, path[ans - 1])));
cout << res;
}
Compilation message
torrent.cpp: In function 'int DFS(int, int, std::pair<int, int>)':
torrent.cpp:40:22: warning: comparison of integer expressions of different signedness: 'int' and 'std::vector<int>::size_type' {aka 'long unsigned int'} [-Wsign-compare]
40 | for(int i = 0; i < res.size(); i++)
| ~~^~~~~~~~~~~~
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
3 ms |
8536 KB |
Output is correct |
2 |
Correct |
2 ms |
8536 KB |
Output is correct |
3 |
Correct |
2 ms |
8540 KB |
Output is correct |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
293 ms |
20448 KB |
Output is correct |
2 |
Correct |
287 ms |
21964 KB |
Output is correct |
3 |
Correct |
323 ms |
23352 KB |
Output is correct |
4 |
Correct |
329 ms |
22640 KB |
Output is correct |
5 |
Correct |
263 ms |
19792 KB |
Output is correct |
6 |
Correct |
292 ms |
20764 KB |
Output is correct |
7 |
Correct |
272 ms |
23788 KB |
Output is correct |