Pagini recente » Cod sursa (job #1269093) | Cod sursa (job #220917) | Cod sursa (job #1439717) | Cod sursa (job #100565) | Cod sursa (job #2392263)
#include <stdio.h>
#include <vector>
const int MAX_N = 100000;
const int SIZE = 320;
int father[1 + MAX_N];
std::vector<int> G[1 + MAX_N];
int pos[1 + MAX_N];
int depth[1 + MAX_N];
int ancestor[1 + MAX_N];
void dfs(int u, int T, int lev) {
depth[u] = lev;
ancestor[u] = T;
if (lev % SIZE == 0)
T = u;
for (int v : G[u])
if (father[u] != v)
dfs(v, T, lev + 1);
}
int lca(int x, int y) {
while (ancestor[x] != ancestor[y]) {
if (depth[x] > depth[y])
x = ancestor[x];
else
y = ancestor[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);
int n, q;
scanf("%d%d", &n, &q);
for (int i = 2; i <= n; i++) {
scanf("%d", &father[i]);
G[father[i]].push_back(i);
G[i].push_back(father[i]);
}
dfs(1, 0, 0);
for (int i = 1; i <= q; i++) {
int x, y;
scanf("%d%d", &x, &y);
printf("%d\n", lca(x, y));
}
return 0;
}