This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
vector<bool> vis;
vector<int> pr;
vector<vector<int>> E;
void dfs_pr(int x, int p = -1) {
pr[x] = p;
for (auto i : E[x]) {
if (i != p) dfs_pr(i, x);
}
}
int dfs(int x) {
vis[x] = true;
vector<int> v;
for (auto i : E[x]) {
if (!vis[i]) v.push_back(dfs(i));
}
sort(v.rbegin(), v.rend());
int mx = 0;
for (int i = 0; i < (int)v.size(); i++) mx = max(mx, v[i] + i + 1);
return mx;
}
int main() {
ios::sync_with_stdio(false); cin.tie(nullptr);
int n, a, b;
cin >> n >> a >> b; a--; b--;
E.assign(n, {});
for (int i = 1; i < n; i++) {
int x, y;
cin >> x >> y;
E[--x].push_back(--y);
E[y].push_back(x);
}
pr.assign(n, 0);
dfs_pr(a);
vector<int> v;
int cur = pr[b];
while (cur != -1) {
v.push_back(cur);
cur = pr[cur];
}
reverse(v.begin(), v.end());
int l = 0, r = (int)v.size() - 1;
while (l <= r) {
int md = (l + r) >> 1;
vis.assign(n, false);
vis[v[md]] = true;
int y = dfs(b);
vis[v[md]] = false;
int x = dfs(a);
if (x <= y) l = md + 1;
else r = md - 1;
}
int ans = INT_MAX;
if (l) {
vis.assign(n, false);
vis[v[l - 1]] = true;
ans = dfs(b);
}
if (l < (int)v.size()) {
vis.assign(n, false);
vis[v[l]] = true;
int z = dfs(b);
vis[v[l]] = false;
ans = min(ans, dfs(a));
}
cout << ans;
}
Compilation message (stderr)
torrent.cpp: In function 'int main()':
torrent.cpp:90:13: warning: unused variable 'z' [-Wunused-variable]
90 | int z = dfs(b);
| ^
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |