Pagini recente » Cod sursa (job #2167951) | Cod sursa (job #2938498) | Cod sursa (job #3191148) | Cod sursa (job #295875) | Cod sursa (job #3247229)
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream f("lca.in");
ofstream g("lca.out");
int father[100005],depth[100005],ind[100005],lg[200005];
pair<int,int> a[20][200005];
vector <int> sons[100005];
vector <int> euler;
queue <int> q;
void parcurgere(int node)
{
euler.push_back(node);
ind[node]=euler.size()-1;
for(auto i:sons[node])
{
parcurgere(i);
euler.push_back(node);
}
}
int main()
{
int n,m;
f>>n>>m;
for(int i=1;i<n;i++)
{
f>>father[i+1];
sons[father[i+1]].push_back(i+1);
}
q.push(1);
while(!q.empty())
{
int x=q.front();
q.pop();
for(auto i:sons[x])
{
depth[i]=depth[x]+1;
q.push(i);
}
}
parcurgere(1);
int l=euler.size();
lg[2]=1;
for(int i=3;i<=l;i++)
lg[i]=lg[i/2]+1;
for(int i=0;i<l;i++)
a[0][i]={depth[euler[i]],euler[i]};
for(int j=1;(1<<j)<l;j++)
for(int i=0;i+(1<<j)-1<l;i++)
a[j][i]=min(a[j-1][i+(1<<(j-1))],a[j-1][i]);
while(m--)
{
int aa,bb,x,y;
f>>aa>>bb;
x=ind[aa], y=ind[bb];
pair<int,int> minn={2*n+1,0};
if(x>y) swap(x,y);
int k=lg[y-x+1];
for(int i=k;i>=0;i--)
if(x+(1<<i)-1<=y)
{
minn=min(minn,a[i][x]);
x+=1<<i;
}
g<<minn.second<<'\n';
}
return 0;
}