Pagini recente » Cod sursa (job #1354005) | Cod sursa (job #2293804) | Cod sursa (job #2250044) | Cod sursa (job #2865019) | Cod sursa (job #2877746)
#include <bits/stdc++.h>
using namespace std;
ifstream f("lca.in");
ofstream g("lca.out");
vector < int > v[100005];
int n,q;
int x,y;
int nodes[200005],depths[200005];
int aa;
bool viz[100005];
int last[100005];
pair < int , int > rmq[200005][20];
pair < int , int > minim(pair < int , int > a, pair < int , int > b) {
if (a.first<b.first) return a;
return b;
}
void read() {
f >> n >> q;
for (int i=2;i<=n;i++) {
f >> x;
v[x].push_back(i);
v[i].push_back(x);
}
}
void dfs(int nod, int depth) {
viz[nod] = 1;
nodes[++aa] = nod; depths[aa] = depth; last[nod] = aa;
for (auto k:v[nod]) {
if (!viz[k]) {
dfs(k,depth+1);
nodes[++aa] = nod; depths[aa] = depth; last[nod] = aa;
}
}
}
void create_rmq(){
for (int i=1;i<=aa;i++) {
rmq[i][0].first = depths[i];
rmq[i][0].second = i;
}
for (int p=1;p<=18;p++) {
for (int i=1;i<=aa-(1<<p);i++) {
rmq[i][p] = minim(rmq[i][p-1],rmq[i+(1<<(p-1))][p-1]);
}
}
}
int ancestor(int a, int b) {
int dif = b-a+1;
int k=0;
while ((1<<k)<=dif) k++;
k--;
pair < int , int > p = minim(rmq[a][k],rmq[b-(1<<k)+1][k]);
return nodes[p.second];
}
void solve() {
dfs(1,0);
create_rmq();
for (int i=1;i<=q;i++) {
f >> x >> y;
g << ancestor(min(last[x],last[y]),max(last[x],last[y])) << '\n';
}
}
int main()
{
read();
solve();
return 0;
}