Pagini recente » Cod sursa (job #1691582) | Cod sursa (job #2976007) | Cod sursa (job #2965148) | Cod sursa (job #2583660) | Cod sursa (job #3245678)
#include <fstream>
#include <algorithm>
#include <cmath>
using namespace std;
ifstream cin("lca.in");
ofstream cout("lca.out");
int v[120][260005];
int nivel[110005];
int n;
int main()
{
int q;
cin>>n>>q;
v[0][1]=0;
for(int i=2;i<=n;i++)
{
cin>>v[0][i];
nivel[i]=nivel[v[0][i]]+1;
}
int l=log2(n)+1;
for(int i=1;i<=l;i++)
{
for(int k=1;k<=n;k++)
{
v[i][k]=v[i-1][v[i-1][k]];
}
}
for(int i=0;i<q;i++)
{
int a,b;
cin>>a>>b;
if(nivel[a]>nivel[b])
{
swap(a,b);
}
//a<b
if(nivel[a]!=nivel[b])
{
int tata=nivel[b]-nivel[a]+1;
int ans=0;
int cur=b;
for(int k=1;k<tata;k++)
{
b=v[0][b];
}
}
//cout<<'\n';
//cout<<a <<" "<<b<<'\n';
int ans=0,t=nivel[b],rez=-1;
for(int pas=(1<<l);pas>0;pas/=2)
{
if(pas<=t && v[pas][a]!=v[pas][b])
{
ans=pas;
a=v[pas][a];
b=v[pas][b];
cout<<a <<" "<<b<<'\n';
}
}
if(a==b)
{
cout<<a;
}
else if(v[0][a]==v[0][b])
{
cout<<v[0][a];
}
else
{
a=v[0][a];
cout<<v[0][a];
}
cout<<'\n';
}
return 0;
}