Pagini recente » Cod sursa (job #2909829) | Cod sursa (job #2234584) | Cod sursa (job #2577873) | Cod sursa (job #2860922) | Cod sursa (job #2447504)
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 100005;
int n, l = 200;
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);
}
int solve(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);
}
batog(1, 0, 0);
while(m){
int x, y;
fin >> x >> y;
fout << solve(x, y) << "\n";
m--;
}
return 0;
}