Pagini recente » Cod sursa (job #3153747) | Cod sursa (job #2343212) | Cod sursa (job #2343303) | Cod sursa (job #2871487) | Cod sursa (job #3263304)
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
ifstream fin("lca.in");
ofstream fout("lca.out");
pair<int,int> rmq[200005][18];
pair<int,int> euler[200005];
int ind[100005];
int n, m, x, y, k, n1, n2;
int p2[200005];
vector<int> v[100005];
void dfs(int nod, int niv) {
ind[nod] = ++k;
euler[k] = {niv, nod};
for (auto nxt:v[nod]) {
dfs(nxt, niv+1);
euler[++k] = {niv, nod};
}
}
void read() {
fin >> n >> m;
for (int i=2;i<=n;i++) {
fin >> x;
v[x].push_back(i);
}
p2[1] = 0;
for (int i=2;i<=2*n;i++) {
p2[i] = p2[i-1];
if ((1<<(p2[i]+1)) <= i) {
p2[i]++;
}
}
}
void create() {
for (int j=0;(1<<j)<=k;j++) {
for (int i=1;i<=k-(1<<j)+1;i++) {
if (j == 0) {
rmq[i][j] = euler[i];
}
else {
rmq[i][j] = min(rmq[i][j-1], rmq[i+(1<<(j-1))][j-1]);
}
}
}
}
void query() {
x = ind[n1]; y = ind[n2];
int l = (y-x+1);
fout << min(rmq[x][p2[l]], rmq[y-(1<<p2[l])+1][p2[l]]).second << '\n';
}
int main() {
read();
dfs(1, 0);
create();
for (int t=1;t<=m;t++) {
fin >> n1 >> n2;
query();
}
return 0;
}