Pagini recente » Cod sursa (job #1713735) | Cod sursa (job #2142536) | Cod sursa (job #1009637) | Cod sursa (job #1395939) | Cod sursa (job #2629033)
#include <bits/stdc++.h>
using namespace std;
#define NMAX 100005
int n, m, father[NMAX], depth[NMAX];
int find_lca(int x, int y) {
while(x != y) {
if(depth[x] > depth[y]) {
x = father[x];
} else {
y = father[y];
}
}
return x;
}
int main() {
freopen("lca.in", "r", stdin);
freopen("lca.out", "w", stdout);
scanf("%d%d", &n, &m);
for(int i = 2; i <= n; i++) {
scanf("%d", &father[i]);
depth[i] = depth[father[i]] + 1;
}
for(int i = 1; i <= m; i++) {
int x, y;
scanf("%d%d", &x, &y);
printf("%d\n", find_lca(x, y));
}
return 0;
}