CSES - Shared codeLink to this code:
https://cses.fi/paste/7aa0a4e885b4ccac380bff/
#include <iostream>
#include <vector>
using ll = long long;
int const nmax = 200000;
int parent[1 + nmax];
int far[1 + nmax];
int level[1 + nmax];
int getLca(int x, int y) {
if(level[x] < level[y])
std::swap(x, y);
while(level[y] < level[x]) {
if(level[y] <= level[far[x]])
x = far[x];
else
x = parent[x];
}
if(x == y)
return x;
while(parent[x] != parent[y]) {
if(far[x] != far[y]) {
x = far[x];
y = far[y];
} else {
x = parent[x];
y = parent[y];
}
}
return parent[x];
}
int main() {
int n, q;
std::cin >> n >> q;
for(int i = 2; i <= n; i++)
std::cin >> parent[i];
level[1] = 1;
for(int i = 2; i <= n; i++) {
level[i] = level[parent[i]] + 1;
int father = parent[i];
int father2 = far[father];
if(far[father2] != 0 && level[father] - level[father2] == level[father2] - level[far[father2]]) {
far[i] = far[father2];
} else
far[i] = father;
}
for(int i = 1;i <= q; i++) {
int x, y;
std::cin >> x >> y;
std::cout << getLca(x, y) << '\n';
}
return 0;
}