// Be name khoda //
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define all(x) x.begin(), x.end()
#define fi first
#define se second
#define pb push_back
const int maxn5 = 1e6 + 10;
const int inf = 1e9;
int tale, mo, dp[maxn5], id[maxn5];
int htotale[maxn5], fen[maxn5];
vector <int> adj[maxn5], ver;
vector <pair<int, int>> av;
inline bool dfs(int v, int par){
if(v == tale){
dp[v] = 0;
htotale[v] = 0;
return true;
}
int mx = 0, smx = 0;
int z = -1;
for(auto u : adj[v]) if(u != par){
bool re = dfs(u, v);
if(re){
z = u;
}
if(dp[u] >= mx){
smx = mx;
mx = dp[u];
}
else
smx = max(smx, dp[u]);
}
if(z == -1){
dp[v] = smx + adj[v].size() - 1;
//cout << "false " << v << ' ' << dp[v] << endl;
return false;
}
htotale[v] = htotale[z] + adj[v].size() - 2 + (v == mo);
for(auto u : adj[v]) if(u != par && u != z){
av.pb({dp[u] + htotale[v], v});
//cout << "aha " << v << ' ' << u << ' ' << dp[u] << ' ' << htotale[v] << endl;
}
ver.pb(v);
return true;
}
inline void add(int id){
for(; id < maxn5; id += id & -id)
fen[id]++;
}
inline int get(int id){
int ret = 0;
for(; id; id -= id & -id)
ret += fen[id];
return ret;
}
inline bool ok(int v){
v = id[v];
return get(v) < v;
}
int main(){
ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
int n, a, b; cin >> n >> a >> b;
a--; b--;
mo = b;
tale = a;
for(int i = 0; i < n - 1; i++){
int a, b; cin >> a >> b;
a--; b--;
adj[a].pb(b);
adj[b].pb(a);
}
assert(a != b);
if(a == b)
return cout << 0 << endl, 0;
dfs(mo, -1);
reverse(all(ver)); // az m be t hast
int pos = 1;
for(auto v : ver){
id[v] = pos++;
}
sort(all(av));
reverse(all(av));
int done = 0;
int mx = 0;
int ans = inf;
for(auto [val, v] : av){
//cout << "& " << val << ' ' << v << endl;
ans = min(ans, done + val);
if(ok(v)){
done++;
add(id[v]);
}
else
break;
}
cout << ans << endl;
}
Compilation message
mousetrap.cpp: In function 'int main()':
mousetrap.cpp:103:9: warning: unused variable 'mx' [-Wunused-variable]
103 | int mx = 0;
| ^~
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
13 ms |
23764 KB |
Output is correct |
2 |
Correct |
14 ms |
23852 KB |
Output is correct |
3 |
Incorrect |
14 ms |
23712 KB |
Output isn't correct |
4 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
291 ms |
59152 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
13 ms |
23764 KB |
Output is correct |
2 |
Correct |
14 ms |
23852 KB |
Output is correct |
3 |
Incorrect |
14 ms |
23712 KB |
Output isn't correct |
4 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
13 ms |
23764 KB |
Output is correct |
2 |
Correct |
14 ms |
23852 KB |
Output is correct |
3 |
Incorrect |
14 ms |
23712 KB |
Output isn't correct |
4 |
Halted |
0 ms |
0 KB |
- |