Pagini recente » Monitorul de evaluare | Cod sursa (job #187814) | Profil denisx304 | Cod sursa (job #2694080) | Cod sursa (job #2846980)
/*
__
_.--"" |
.----. _.-' |/\| |.--.
| |__.-' _________| |_) _______________
| .-""-.""""" ___, `----'")) __ .-""-.""""--._
'-' ,--. ` |Cezar| .---. |:.| ' ,--. ` _`.
( ( ) ) __| 7 |__\\|// _..-- \/ ( ( ) )--._".-.
. `--' ;\__________________..--------. `--' ;--------'
`-..-' `-..-'
*/
#include <iostream>
#include <fstream>
#include <bitset>
using namespace std;
const int N = 1e5 + 5;
int niv[N];
int tati[19][N];
int nivell(int x){
if(x==tati[0][x])
return 0;
if(niv[tati[0][x]] == 0)
niv[x] = 1 + nivell(tati[0][x]);
else{
niv[x] = 1 + niv[tati[0][x]];
return 0;
}
}
int lca(int x, int y){
int niv1 = niv[x];
int niv2 = niv[y];
if(niv1<niv2) {
swap(niv1, niv2);
swap(x,y);
}
if(niv1>niv2){
for(int i=17;i>=0;i--){
if(niv1 - (1<<i) >= niv2){
x = tati[i][x];
niv1 = niv[x];
}
}
}
for(int i=17;i>=0;i--){
if(niv1 - (1<<i) >=1 && tati[i][x]!=tati[i][y]){
x = tati[i][x];
y = tati[i][y];
niv1 = niv[x];
}
}
if(x == y)
return x;
return tati[0][x];
}
int main() {
ifstream in("lca.in");
ofstream out("lca.out");
int n,m;
in>>n>>m;
for(int i=2;i<=n;i++){
in>>tati[0][i];
}
for(int i = 1;i<18;i++) {
for (int j = 1; j <= n; j++)
tati[i][j] = tati[i - 1][tati[i - 1][j]];
}
for(int i=1;i<=n;i++){
if(niv[i] == 0)
nivell(i);
}
int x,y;
for(int i=0;i<m;i++){
in>>x>>y;
out<<lca(x,y)<<'\n';
}
return 0;
}