Pagini recente » Cod sursa (job #1740297) | Cod sursa (job #687149) | Cod sursa (job #2221465) | Cod sursa (job #1910998) | Cod sursa (job #2908410)
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
const int N = 1e5;
const int L = 17;
int t[L][N+1], ti[N+1], to[N+1], emax[N+1];
vector <int> fii[N+1];
int timp;
void dfs(int x) {
ti[x] = ++timp;
for(auto y: fii[x])
dfs(y);
to[x] = ++timp;
}
bool este_stramos(int x, int y) {
return (ti[x] <= ti[y] && to[y] <= to[x]);
}
int lca(int x, int y) {
if(este_stramos(x, y))
return x;
for(int e = emax[x]; e >= 0; e--) {
if(t[e][x] != 0 && !este_stramos(t[e][x], y))
x = t[e][x];
}
return t[0][x];
}
int main() {
ifstream fin("lca.in");
ofstream fout("lca.out");
int n, nq;
fin >> n >> nq;
for(int i = 2; i <= n; i++) {
fin >> t[0][i];
fii[t[0][i]].push_back(i);
}
for(int e = 1; (1 << e) <= n; e++) {
for(int i = 1; i <= n; i++) {
t[e][i] = t[e-1][t[e-1][i]];
if (t[e][i] != 0)
emax[i] = e;
}
}
dfs(1);
for(int i = 0; i < nq; i++) {
int x, y;
fin >> x >> y;
fout << lca(x, y) << "\n";
}
return 0;
}