#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 1000005;
vector<int> adj[N];
int upCost[N];
int downCost[N];
int p[N];
vector<vector<int>> sideNodes;
int n, t, m;
void dfs(int node, int par) {
p[node] = par;
for (int next : adj[node]) {
if (next == par) continue;
dfs(next, node);
}
}
void calcDown(int node, int depth) {
if (adj[node].size() == 1) {
downCost[node] = depth;
return;
}
if (adj[node].size() == 2) {
downCost[node] = depth + 1;
return;
}
array<int, 2> most{0, 0};
for (int next : adj[node]) {
if (next == p[node]) continue;
calcDown(next, depth + 1);
if (downCost[next] > most[1]) most[1] = downCost[next];
if (most[0] < most[1]) swap(most[0], most[1]);
}
downCost[node] = adj[node].size() - 2 + most[1];
}
void goUp(int node, int prev = -1) {
if (node == t) return;
if (prev != -1)upCost[node] = adj[node].size() - 2;
else upCost[node] = adj[node].size() - 1;
goUp(p[node], node);
upCost[node] += upCost[p[node]];
vector<int> curSideNodes;
for (int next : adj[node]) {
if (next == prev || next == p[node]) continue;
curSideNodes.push_back(next);
upCost[next] = upCost[node] - 1;
calcDown(next, 1);
}
sideNodes.push_back(curSideNodes);
sort(sideNodes.rbegin(), sideNodes.rend());
}
bool poss(int most) {
int already = 0;
int canHave = 1;
for (vector<int>& nodesVector : sideNodes) {
int exactlyMost = 0;
int moreThanMost = 0;
for (int i : nodesVector) {
if (already + downCost[i] + upCost[i] > most) {
if (already < canHave) already++;
else return false;
}
}
canHave++;
}
return true;
}
int bs() {
int a = 0;
int b = 2 * n;
int res = -1;
while (a <= b) {
int mid =(a +b ) / 2;
//cout << a<< " " << b << " "<< mid << " " << poss(mid) << "\n";
if (poss(mid)) {
res = mid;
b = mid - 1;
} else a = mid + 1;
}
return res;
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cin >> n >> t >> m;
for (int i = 0; i < n - 1; i++) {
int a, b;
cin >> a >> b;
adj[a].push_back(b);
adj[b].push_back(a);
}
dfs(t, -1);
goUp(m);
cout << bs() << "\n";
}
/*
10 1 2
1 2
2 3
2 4
3 9
3 5
4 7
4 6
6 8
7 10
*/
Compilation message
mousetrap.cpp: In function 'bool poss(int)':
mousetrap.cpp:67:13: warning: unused variable 'exactlyMost' [-Wunused-variable]
67 | int exactlyMost = 0;
| ^~~~~~~~~~~
mousetrap.cpp:68:13: warning: unused variable 'moreThanMost' [-Wunused-variable]
68 | int moreThanMost = 0;
| ^~~~~~~~~~~~
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
15 ms |
23756 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
363 ms |
62832 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
15 ms |
23756 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
15 ms |
23756 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |