Pagini recente » Cod sursa (job #2255482) | Cod sursa (job #837560) | Cod sursa (job #1837484) | Cod sursa (job #1472593) | Cod sursa (job #2441570)
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 100005;
int n, l = 200, frnod;
int anc[MAXN];
int radanc[MAXN], niv[MAXN];
vector<int> graf[MAXN];
void batog(int nod, int tata, int nivel){
radanc[nod] = tata;
niv[nod] = nivel;
if(nivel % l == 0) tata = nod;
for(auto x:graf[nod])
batog(x, tata, nivel + 1);
}
void prec(){
batog(1, 0, 0);
}
int solve1(int x, int y){
while(x != y){
if(x > y) x = anc[x];
else y = anc[y];
}
return x;
}
int solve2(int x, int y){
while(radanc[x] != radanc[y]){
if(niv[x] > niv[y]) x = radanc[x];
else y = radanc[y];
}
while(x != y){
if(niv[x] > niv[y]) x = anc[x];
else y = anc[y];
}
return x;
}
int main()
{
ifstream fin("lca.in");
ofstream fout("lca.out");
int m;
fin >> n >> m;
for(int i = 2; i <= n; ++i){
fin >> anc[i];
graf[anc[i]].push_back(i);
}
prec();
while(m){
int x, y;
fin >> x >> y;
fout << solve2(x, y) << "\n";
m--;
}
return 0;
}