Pagini recente » Cod sursa (job #2899298) | Cod sursa (job #77355) | Cod sursa (job #2452613) | Cod sursa (job #3156805) | Cod sursa (job #3297755)
#include <bits/stdc++.h>
#define NMAX 100000
#define LOG 18
using namespace std;
ifstream fin("lca.in");
ofstream fout("lca.out");
int n, m, x, a, b;
vector<int> arb[NMAX + 2];
int niv[NMAX + 2];
int up[NMAX + 2][LOG];
void DFS_binar(int nod, int par) {
niv[nod] = niv[par] + 1;
for (int vec : arb[nod]) {
if (vec == par) {
continue;
}
up[vec][0] = nod;
for (int j = 1; j < LOG; j++) {
up[vec][j] = up[up[vec][j - 1]][j - 1];
}
DFS_binar(vec, nod);
}
}
int LCA(int x, int y) {
if (niv[x] < niv[y]) {
swap(x, y);
}
for (int i = LOG - 1; i >= 0; i--) {
if (niv[x] - (1 << i) >= niv[y]) {
x = up[x][i];
}
}
if (x == y) {
return x;
}
for (int i = LOG - 1; i >= 0; i--) {
if (up[x][i] != up[y][i]) {
x = up[x][i];
y = up[y][i];
}
}
return up[x][0];
}
int main() {
ios_base::sync_with_stdio(false);
fin.tie(NULL);
fout.tie(NULL);
fin >> n >> m;
for (int i = 2; i <= n; i++) {
fin >> x;
arb[x].emplace_back(i);
arb[i].emplace_back(x);
}
DFS_binar(1, 0);
while (m--) {
fin >> a >> b;
fout << LCA(a, b) << '\n';
}
return 0;
}