Pagini recente » Cod sursa (job #348351) | Cod sursa (job #1639452) | Cod sursa (job #2321065) | Cod sursa (job #4065) | Cod sursa (job #2629134)
#include <bits/stdc++.h>
using namespace std;
#define NMAX 100005
int n, m, father[NMAX], depth[NMAX], anc[NMAX], maxD;
vector <int> tree[NMAX];
void getAncestors(int node, int ancestor, int d) {
anc[node] = ancestor;
if(depth[node] % d == 0) {
ancestor = node;
}
for(auto son : tree[node]) {
getAncestors(son, ancestor, d);
}
}
int find_lca(int x, int y) {
while(anc[x] != anc[y]) {
if(depth[x] > depth[y]) {
x = anc[x];
} else {
y = anc[y];
}
}
while(x != y) {
if(depth[x] > depth[y]) {
x = father[x];
} else {
y = father[y];
}
}
return x;
}
int rad(int x) {
if(sqrt(x) == (int)sqrt(x)) return sqrt(x) - 1;
return (int)sqrt(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]);
tree[father[i]].push_back(i);
depth[i] = depth[father[i]] + 1;
maxD = max(depth[i], maxD);
}
getAncestors(1, 1, rad(maxD));
for(int i = 1; i <= m; ++i) {
int x, y;
scanf("%d%d", &x, &y);
printf("%d\n", find_lca(x, y));
}
return 0;
}