Pagini recente » Cod sursa (job #633901) | Cod sursa (job #2677863) | Cod sursa (job #1499108) | Cod sursa (job #2738904) | Cod sursa (job #932482)
Cod sursa(job #932482)
#include<cstdio>
#include<cmath>
#include<list>
#include<algorithm>
#define infile "lca.in"
#define outfile "lca.out"
#define nMax 100005
using namespace std;
list < int > v[nMax];
int T[nMax], P[nMax], L[nMax];
int H;
int N, M;
void DFS(int x){
L[x] = L[T[x]] + 1;
H = max(H, L[x]);
for(list < int > :: iterator it = v[x].begin(); it != v[x].end(); ++it)
DFS(*it);
}
void DF(int x, int up){
P[x] = up;
if(L[x] % H == 1)
up = x;
for(list < int > :: iterator it = v[x].begin(); it != v[x].end(); ++it)
DF(*it, up);
}
int lca(int x, int y){
while(P[x] != P[y])
if(L[x] > L[y])
x = P[x];
else
y = P[y];
while(x != y)
if(L[x] > L[y])
x = T[x];
else
y = T[y];
return x;
}
int main(){
freopen(infile, "r", stdin);
freopen(outfile, "w", stdout);
scanf("%d %d", &N, &M);
for(int x = 2; x <= N; ++ x){
scanf("%d", &T[x]);
v[T[x]].push_back(x);
}
DFS(1);
H = (int) sqrt(double(N)) + 1;
DF(1, 1);
int x, y;
while(M--){
scanf("%d %d", &x, &y);
printf("%d\n", lca(x,y));
}
fclose(stdin);
fclose(stdout);
return 0;
}