Pagini recente » Cod sursa (job #3170980) | Cod sursa (job #2655714) | Cod sursa (job #1566528) | Cod sursa (job #1693617) | Cod sursa (job #738595)
Cod sursa(job #738595)
#include <iostream>
#include <fstream>
#include <cmath>
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(){
ifstream in("lca.in");
ofstream out("lca.out");
in >> N >> M;
A[1] = 0;
for(int i = 2; i <= N; ++i)
in >> A[i];
compute_heights();
preprocess();
for(int i = 0; i < M; ++i){
int x, y;
in >> x >> y;
int ret = solve(x, y);
out << ret << endl;
}
return 0;
}