Pagini recente » Cod sursa (job #870728) | Cod sursa (job #1607137) | Cod sursa (job #2949414) | Cod sursa (job #431715) | Cod sursa (job #920612)
Cod sursa(job #920612)
#include<cstdio>
#include<list>
#include<algorithm>
#define pb push_back
#define nxt (*it)
#define FOR(i,a,b)\
for(int i=a; i<=b; ++i)
#define ALL(g)\
for(typeof(g.begin()) it=g.begin(); it!=g.end(); ++it)
#define infile "lca.in"
#define outfile "lca.out"
#define nMax 100005
#define logMax 20
using namespace std;
int E[nMax << 1], L[nMax << 1], P[nMax];
int Log[nMax << 1];
int DP[logMax][nMax << 2];
list < int > v[nMax];
int N, M;
void DF(int x, int lev){
E[P[x] = ++E[0]] = x;
L[E[0]] = lev;
ALL(v[x]){
DF(nxt, lev + 1);
E[++E[0]] = x;
L[E[0]] = lev;
}
}
void RMQ(){
FOR(i,2,E[0])
Log[i] = Log[i >> 1] + 1;
FOR(i,1,E[0])
DP[0][i] = i;
FOR(i,1,Log[E[0]])
FOR(j,1, E[0] - (1<<i)){
int l = 1 << (i - 1);
DP[i][j] = DP[i-1][j];
if(L[DP[i-1][j + l]] < L[DP[i][j]])
DP[i][j] = DP[i-1][j + l];
}
}
int LCA(int x, int y){
int px = P[x], py = P[y];
if(px > py)
swap(px, py);
int k = Log[py - px +1];
int rez = DP[k][px];
if(L[rez] > L[DP[k][py - (1 << k) + 1]])
rez = DP[k][py - (1 << k) + 1];
return E[rez];
}
int main(){
freopen(infile, "r", stdin);
freopen(outfile, "w", stdout);
scanf("%d %d", &N, &M);
int x, y;
FOR(i,2,N){
scanf("%d", &x);
v[x].pb(i);
}
DF(1,0);
RMQ();
while(M--){
scanf("%d %d", &x, &y);
printf("%d\n", LCA(x,y));
}
fclose(stdin);
fclose(stdout);
return 0;
}