Pagini recente » Cod sursa (job #1949663) | Cod sursa (job #2352201) | Cod sursa (job #681557) | Cod sursa (job #205453) | Cod sursa (job #2365580)
#include<bits/stdc++.h>
using namespace std;
const int maxN=(1e5)+5;
vector<int> v[maxN];
int depth[maxN],anc[maxN][20];
const int dim=(1e5);
char buff[dim+5];
int pos=0;
inline void dfs(int nod)
{
for(auto it:v[nod])
{
depth[it]=1+depth[nod];
dfs(it);
}
}
inline void read(int &nr)
{
nr=0;
while(!isdigit(buff[pos]))
{
pos++;
if(pos==dim)
{
pos=0;
fread(buff,1,dim,stdin);
}
}
while(isdigit(buff[pos]))
{
nr=nr*10+buff[pos]-'0';
pos++;
if(pos==dim)
{
pos=0;
fread(buff,1,dim,stdin);
}
}
}
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);
fread(buff,1,dim,stdin);
read(n);
read(q);
for(int i=2;i<=n;i++)
{
read(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--)
{
read(x);
read(y);
printf("%d\n",lca(x,y));
}
return 0;
}