Pagini recente » Cod sursa (job #709163) | Cod sursa (job #1734924) | Cod sursa (job #1885662) | Cod sursa (job #192061) | Cod sursa (job #2604869)
#include <iostream>
#include <fstream>
using namespace std;
ifstream in("lca.in");
ofstream out("lca.out");
const int L = 18;
int n, m, nr, timp, vf[100001], urm[100001], lst[100001], t[L][100001], tb[100001], to[100001];
void add(int x, int y) {
vf[++nr] = y;
urm[nr] = lst[x];
lst[x] = nr;
}
void dfs(int x) {
tb[x] = ++timp;
int y;
for (int p = lst[x]; p != 0; p = urm[p]) {
y = vf[p];
if (tb[y] == 0) {
dfs(y);
t[0][y] = x;
}
}
to[x] = ++timp;
}
int lca(int x, int y) {
if (tb[x] <= tb[y] && to[y] <= to[x])
{
return x;
}
int pas = L - 1;
int s;
while (pas >= 0) {
s = t[pas][x];
if (s != 0 && ((tb[s] > tb[y]) || (to[s] < to[y]))) {
x = s;
}
pas--;
}
return t[0][x];
}
int main() {
in >> n >> m;
for (int i = 2; i <= n; i++) {
int a;
in >> a;
add(a, i);
}
dfs(1);
for (int i = 1; (1 << i) <= n; i++){
for (int j = 1; j <= n; j++){
t[i][j] = t[i - 1][t[i - 1][j]];
}
}
for (int i = 1; i <= m; i++) {
int x, y;
in >> x >> y;
out << lca(x, y) << '\n';
}
return 0;
}