Pagini recente » Cod sursa (job #1690057) | Cod sursa (job #1637633) | Cod sursa (job #245159) | Cod sursa (job #3247449) | Cod sursa (job #738709)
Cod sursa(job #738709)
#include <cmath>
#include <cstdio>
#include <algorithm>
using namespace std;
#define NMAX 100005
int N, M, A[NMAX], h[NMAX], P[NMAX];
int find_height(int i){
if(h[i] != -1)
return h[i];
h[i] = find_height(A[i]) + 1;
}
void compute_heights(){
h[1] = 0;
for(int i = 2; i <= N; ++i) h[i] = -1;
for(int i = 2; i <= N; ++i)
if(h[i] == -1)
find_height(i);
}
int getMaxHeight(){
int m = 0;
for(int i = 1; i <= N; ++i)
m = max(h[i], m);
return m;
}
void preprocess(){
int bucket = static_cast<int>(sqrt(getMaxHeight() + 1));
for(int i = 1; i <= N; ++i){
if(h[i] < bucket) P[i] = 1;
else{
if(h[i] % bucket == 0)
P[i] = A[i];
else
P[i] = P[A[i]];
}
}
}
int solve(int x, int y){
while(P[x] != P[y]){
if(h[x] < h[y])
y = P[y];
else
x = P[x];
}
while(x != y){
if(h[x] < h[y])
y = A[y];
else
x = A[x];
}
}
int main(){
freopen("lca.in", "rt", stdin);
freopen("lca.out", "wt", stdout);
scanf("%d %d", &N, &M);
A[1] = 0;
for(int i = 2; i <= N; ++i)
scanf("%d", &A[i]);
compute_heights();
preprocess();
for(int i = 0; i < M; ++i){
int x, y;
scanf("%d %d", &x, &y);
int ret = solve(x, y);
printf("%d\n", ret);
}
return 0;
}