Aprendi LCA!
This commit is contained in:
parent
7ad7a196f1
commit
e6633ede97
74
Problems/SphereOJ/lcasq.cpp
Normal file
74
Problems/SphereOJ/lcasq.cpp
Normal file
@ -0,0 +1,74 @@
|
|||||||
|
#include <bits/stdc++.h>
|
||||||
|
|
||||||
|
using namespace std;
|
||||||
|
|
||||||
|
vector<vector<int>> bl;
|
||||||
|
vector<vector<int>> adj;
|
||||||
|
vector<int> depth;
|
||||||
|
int bllog2;
|
||||||
|
|
||||||
|
void ddfs(int o){
|
||||||
|
for(int nv : adj[o]){
|
||||||
|
depth[nv] = depth[o]+1;
|
||||||
|
ddfs(nv);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int lca(int a, int b){
|
||||||
|
if(depth[a] < depth[b]) swap(a,b);
|
||||||
|
|
||||||
|
int k = depth[a] - depth[b];
|
||||||
|
for(int p = bllog2; p >= 0; p--){
|
||||||
|
if(k & (1 << p)){
|
||||||
|
a = bl[a][p];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if(a == b) return a;
|
||||||
|
|
||||||
|
for(int p = bllog2; p >= 0; p--){
|
||||||
|
if(bl[a][p] != bl[b][p]){
|
||||||
|
a = bl[a][p], b = bl[b][p];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return bl[a][0];
|
||||||
|
}
|
||||||
|
|
||||||
|
int main(){
|
||||||
|
ios::sync_with_stdio(false);
|
||||||
|
|
||||||
|
int n,q, m, x,y;
|
||||||
|
cin >> n;
|
||||||
|
|
||||||
|
adj.assign(n, vector<int>());
|
||||||
|
bllog2 = 32 - __builtin_clz(n);
|
||||||
|
bl.assign(n, vector<int>(bllog2+1));
|
||||||
|
bl[0][0] = 0;
|
||||||
|
for(int i = 0; i < n; i++){
|
||||||
|
cin >> m;
|
||||||
|
while(m--){
|
||||||
|
cin >> x;
|
||||||
|
bl[x][0] = i;
|
||||||
|
adj[i].push_back(x);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for(int p = 1; p <= bllog2; p++){
|
||||||
|
for(int i = 0; i < n; i++){
|
||||||
|
x = bl[i][p-1];
|
||||||
|
bl[i][p] = bl[x][p-1];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
depth.resize(n);
|
||||||
|
depth[0] = 0;
|
||||||
|
ddfs(0);
|
||||||
|
|
||||||
|
cin >> q;
|
||||||
|
while(q--){
|
||||||
|
cin >> x >> y;
|
||||||
|
cout << lca(x,y) << '\n';
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
BIN
Problems/SphereOJ/out
Executable file
BIN
Problems/SphereOJ/out
Executable file
Binary file not shown.
Loading…
x
Reference in New Issue
Block a user