Pagini recente » Cod sursa (job #10513) | Cod sursa (job #154063) | Cod sursa (job #2653525) | Cod sursa (job #548080) | Cod sursa (job #2365561)
#include<bits/stdc++.h>
using namespace std;
const int maxN=(1e5)+5;
vector<int> v[maxN];
int depth[maxN],anc[maxN][19];
inline void dfs(int nod)
{
for(auto it:v[nod])
{
depth[it]=1+depth[nod];
dfs(it);
}
}
inline int lca(int x,int y)
{
if(depth[x]<depth[y]) swap(x,y);
for(int step=17;step>=0;step--)
if(depth[anc[x][step]]>=depth[y]) x=anc[x][step];
// x=anc[x][0];
if(x==y) return x;
for(int step=17;step>=0;step--)
if(anc[x][step]!=anc[y][step])
{
x=anc[x][step];
y=anc[y][step];
}
return anc[x][0];
}
int n,q,x,y;
int main()
{
freopen("lca.in","r",stdin);
freopen("lca.out","w",stdout);
scanf("%d%d",&n,&q);
for(int i=2;i<=n;i++)
{
scanf("%d",&anc[i][0]);
v[anc[i][0]].push_back(i);
}
depth[1]=1;
dfs(1);
for(int j=1;j<=17;j++)
for(int i=1;i<=n;i++)
anc[i][j]=anc[anc[i][j-1]][j-1];
while(q--)
{
scanf("%d%d",&x,&y);
printf("%d\n",lca(x,y));
}
return 0;
}