Pagini recente » Cod sursa (job #2208703) | Cod sursa (job #868958) | Cod sursa (job #921388) | Cod sursa (job #796611) | Cod sursa (job #634594)
Cod sursa(job #634594)
#include<cstdio>
#define N 100005
int p[N];
int mark[N];
int main() {
int n, m;
freopen("lca.in","r",stdin);
freopen("lca.out","w",stdout);
scanf("%d %d",&n, &m);
for(int i = 2; i <= n; i++)
scanf("%d",&p[i]);
for(int i = 1; i <= m; i++) {
int x, y, res = 1;
scanf("%d %d",&x, &y);
while(1) {
if (mark[x] == i && x != 0) {res = x; break;}
mark[x] = i;
if (mark[y] == i && y != 0) {res = y; break;}
mark[y] = i;
if(x != 0)
x = p[x];
if(y != 0)
y = p[y];
}
printf("%d\n", res);
}
}