Pagini recente » Cod sursa (job #645530) | Cod sursa (job #641349) | Cod sursa (job #200191) | Cod sursa (job #824971) | Cod sursa (job #2604476)
#include <fstream>
#include <vector>
#include <bitset>
#include <climits>
using namespace std;
ifstream cin("lca.in");
ofstream cout("lca.out");
const int lim=1e5+3,limarb=128024;
vector<int> vec[lim];
bitset<lim> ok;
pair<int,int> tree[2*limarb+3];
int nr=0;
int poz[lim];
int depth[lim];
void add(int k,int x,int y)
{
k+=limarb;
tree[k]={x,y};
for(k/=2;k>0;k/=2)
tree[k]=min(tree[2*k],tree[2*k+1]);
}
int rasp(int l,int r)
{
l+=limarb;
r+=limarb;
pair<int,int> ans={INT_MAX,0};
while(l<=r)
{
if(l%2==1) ans=min(ans,tree[l++]);
if(r%2==0) ans=min(ans,tree[r--]);
l/=2; r/=2;
}
return ans.second;
}
void dfs(int nod)
{
poz[nod]=++nr;
add(nr,depth[nod],nod);
ok[nod]=1;
for(auto x:vec[nod])
if(!ok[x])
{
depth[x]=depth[nod]+1;
dfs(x);
poz[nod]=++nr;
add(nr,depth[nod],nod);
}
ok[nod]=0;
}
int main()
{
int n,q;
cin>>n>>q;
for(int i=2;i<=n;++i)
{
int x;
cin>>x;
vec[x].push_back(i);
}
dfs(1);
while(q--)
{
int x,y;
cin>>x>>y;
cout<<rasp(min(poz[x],poz[y]),max(poz[x],poz[y]))<<endl;
}
return 0;
}