Pagini recente » Cod sursa (job #1035071) | Cod sursa (job #2430288) | Cod sursa (job #1910926) | Cod sursa (job #243148) | Cod sursa (job #2441484)
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 100005, RAD = 316;
int n;
int anc[MAXN], radanc[MAXN];
int solve1(int x, int y){
while(x != y && x != anc[y] && y != anc[x]){
if(x > y) x = anc[x];
else if(x < y) y = anc[y];
}
if(x == y || x == anc[y]) return x;
else return y;
}
int solve2(int x, int y){
while(x != y && x != anc[y] && y != anc[x]){
if(x > y){
if(x - y < RAD) x = anc[x];
else x = radanc[x];
}
else if(x < y){
if(y - x < RAD) y = anc[y];
else y = radanc[y];
}
}
if(x == y || x == anc[y]) return x;
else return y;
}
int main()
{
ifstream fin("lca.in");
ofstream fout("lca.out");
int m;
fin >> n >> m;
anc[1] = 1;
for(int i = 2; i <= n; ++i)
fin >> anc[i];
for(int i = 2; i <= n; ++i){
int cnt = 0, str = i;
while(str < 1 && cnt < RAD){
str = anc[str];
cnt++;
}
if(cnt == RAD) radanc[i] = str;
}
while(m){
int x, y;
fin >> x >> y;
fout << solve2(x, y) << "\n";
m--;
}
return 0;
}