#include <bits/stdc++.h>
using namespace std;
#define pii pair<int, int>
#define fi first
#define se second
const int N = 3e5+5;
int n, a, b, trace[N], dp[N], ans = N;
vector <pii> path;
vector <int> g[N];
void dfs(int u, int p) {
for(int v:g[u]) if(v != p) {
dfs(v, u);
trace[v] = u;
}
}
void dfs2(int u, int p, int E) {
vector <int> child;
for(int v:g[u]) {
if(v == p or (u==path[E].fi and v == path[E].se) or (u==path[E].se and v==path[E].fi)) continue;
dfs2(v, u, E);
child.emplace_back(dp[v]);
}
sort(child.begin(), child.end());
for(int i = 0; i < child.size(); ++i) {
dp[u] = max(dp[u], child[i] + (int)child.size() - i);
}
}
int val(int v, int E) {
dfs2(v, v, E);
return dp[v];
}
bool check(int numE) {
memset(dp, 0, sizeof(dp));
int vala = val(a, numE), valb = val(b, numE);
ans = min(ans, max(vala, valb));
return (val(a, numE) > val(b, numE));
}
void binary_search() {
int left = 0, right = path.size()-1;
while(left <= right) {
int mid = (left + right) >> 1;
if(check(mid)) {
left = mid + 1; // near a
}
else
right = mid - 1; // near b
}
cout << ans << '\n';
}
signed main() {
ios_base::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
if(fopen("test.inp", "r")) freopen("test.inp", "r", stdin);
cin >> n >> a >> b;
for(int i = 1; i < n; ++i) {
int u, v; cin >> u >> v;
g[u].emplace_back(v);
g[v].emplace_back(u);
}
dfs(a, a);
int tmp = b;
while(tmp != a) {
path.emplace_back(tmp, trace[tmp]);
tmp = trace[tmp];
}
binary_search();
}
Compilation message
torrent.cpp: In function 'void dfs2(int, int, int)':
torrent.cpp:28:22: warning: comparison of integer expressions of different signedness: 'int' and 'std::vector<int>::size_type' {aka 'long unsigned int'} [-Wsign-compare]
28 | for(int i = 0; i < child.size(); ++i) {
| ~~^~~~~~~~~~~~~~
torrent.cpp: In function 'int main()':
torrent.cpp:62:39: warning: ignoring return value of 'FILE* freopen(const char*, const char*, FILE*)' declared with attribute 'warn_unused_result' [-Wunused-result]
62 | if(fopen("test.inp", "r")) freopen("test.inp", "r", stdin);
| ~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
3 ms |
8796 KB |
Output is correct |
2 |
Correct |
3 ms |
8796 KB |
Output is correct |
3 |
Correct |
2 ms |
8792 KB |
Output is correct |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
609 ms |
22100 KB |
Output is correct |
2 |
Correct |
596 ms |
23536 KB |
Output is correct |
3 |
Correct |
454 ms |
25076 KB |
Output is correct |
4 |
Correct |
479 ms |
24444 KB |
Output is correct |
5 |
Correct |
521 ms |
21392 KB |
Output is correct |
6 |
Correct |
443 ms |
21992 KB |
Output is correct |
7 |
Correct |
456 ms |
25720 KB |
Output is correct |