Pagini recente » Cod sursa (job #3310177) | Cod sursa (job #2867002) | Cod sursa (job #461368) | Cod sursa (job #27950) | Cod sursa (job #3328465)
#include <bits/stdc++.h>
#define victor vector
using namespace std;
ifstream fin("lca.in");
ofstream fout("lca.out");
int n,q,i,x,y;
const int lim=100010;
int viz[lim],depth[lim],s[lim*4],sz,first[lim];
victor <int> v[lim],zh;
void dfs(int x,int step)
{
viz[x]=1;
depth[x]=step;
zh.push_back(x);
for(auto k:v[x])
{
if(viz[k]==0)
{
dfs(k,step+1);
zh.push_back(x);
}
}
}
int query(int l,int r)
{
l+=sz;
r+=sz;
int sol=INT_MAX,af=-1;
while(l<=r)
{
if(l%2==1)
{
if(s[l]!=INT_MAX&&depth[s[l]]<sol)
{
sol=depth[s[l]];
af=s[l];
}
}
if(r%2==0)
{
if(s[r]!=INT_MAX&&depth[s[r]]<sol)
{
sol=depth[s[r]];
af=s[r];
}
}
l=(l+1)/2;
r=(r-1)/2;
}
return af;
}
int lca(int x,int y)
{
int rx=first[x];
int ry=first[y];
if(rx>ry)
{
swap(rx,ry);
}
return query(rx,ry);
}
int main()
{
ios_base::sync_with_stdio(false);
fin.tie(NULL);fout.tie(NULL);
fin>>n>>q;
for(i=1;i<=n-1;i++)
{
fin>>x;
v[x].push_back(i+1);
}
dfs(1,0);
for(i=1;i<=n;i++)
first[i]=-1;
for(auto x=0;x<zh.size();x++)
{
if(first[zh[x]]==-1){first[zh[x]]=x;}
}
sz=1;
while(sz<(int)zh.size())sz<<=1;
for(i=0;i<zh.size();i++)
s[sz+i]=zh[i];
for(i=sz+zh.size();i<2*sz;i++)
s[i]=-1;
for(i=sz-1;i>=1;i--)
{
int st=s[i*2];
int dr=s[i*2+1];
if(st==-1)s[i]=dr;
else if(dr==-1)s[i]=st;
else
{
if(depth[st]<depth[dr])s[i]=st;
else s[i]=dr;
}
}
while(q--)
{
fin>>x>>y;
fout<<lca(x,y)<<'\n';
}
return 0;
}