Pagini recente » Statistici Luca Voinescu (LucaYaya) | Profil bytz | Rating Radu Cebotari (tntradu) | Rating Ureche Florin Alexandru (AlexandruX1) | Cod sursa (job #2942489)
#include <bits/stdc++.h>
using namespace std;
ifstream in("lca.in");
ofstream out("lca.out");
int n,m,v[100005],v2[100005],nivel[100005];
vector<int> graf[100005];
const int HMAX=300;
void dfs(int nod,int nod1,int lvl)
{
nivel[nod]=lvl;
v2[nod]=nod1;
if(lvl%HMAX==0) nod1=nod;
for(auto x:graf[nod])
dfs(x,nod1,lvl+1);
}
int main()
{
int n,m;
in>>n>>m;
for(int i=2;i<=n;i++)
{
in>>v[i];
graf[v[i]].push_back(i);
}
dfs(1,1,0);
while(m--)
{
int x,y;
in>>x>>y;
while(v2[x]!=v2[y])
{
if(nivel[x]>nivel[y])
x=v2[x];
else
y=v2[y];
}
while(x!=y)
{
if(nivel[x]>nivel[y])
x=v[x];
else
y=v[y];
}
out<<x<<"\n";
}
return 0;
}