Pagini recente » Cod sursa (job #1034412) | Cod sursa (job #3177727) | Cod sursa (job #2661011) | Cod sursa (job #23140) | Cod sursa (job #3226736)
#include <bits/stdc++.h>
#define pii pair<int,int>
using namespace std;
const int LGMAX = 26;
const int NMAX = 1e5;
int main() {
freopen("lca.in","r",stdin);
freopen("lca.out","w",stdout);
int n,m,x,y;
cin>>n>>m;
vector<vector<int>> r(LGMAX+1,vector<int>(NMAX+1));
for(int i=2;i<=n;i++) cin>>r[0][i];
for(int l=1;l<LGMAX;l++)
for(int i=1;i<=n;i++)
r[l][i] = r[l-1][r[l-1][i]];
vector<int> depth(n+1);
function<void(int)> dfs_depth = [&](int p){
for(int i=1;i<=n;i++)
if(r[0][i]==p){
depth[i] = depth[p] + 1;
dfs_depth(i);
}
};
dfs_depth(1);
function<int(int , int)> _lca = [&](int x, int y){
if(depth[x]<depth[y]) swap(x,y);
for(int l = LGMAX;l>=0;l--)
if(depth[x] - (1<<l)>=depth[y])
x = r[l][x];
if(x == y) return x;
for(int l = LGMAX;l>=0;l--)
if(depth[x] - (1<<l)>=0 && r[l][x]!=r[l][y])
x = r[l][x],y=r[l][y];
return r[0][x];
};
while(m--){
cin>>x>>y;
cout<<_lca(x,y)<<'\n';
}
return 0;
}