Pagini recente » Cod sursa (job #2516100) | Cod sursa (job #238231) | Cod sursa (job #2787284) | Cod sursa (job #1735770) | Cod sursa (job #2883032)
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
ifstream fin("lca.in");
ofstream fout("lca.out");
const int MAX=1e5+5;
const int LOG=18;
int n,m,up[LOG][MAX],depth[MAX],lg[MAX];
vector < int > children[MAX];
void DFS(int nod)
{
depth[nod]=depth[up[0][nod]]+1;
for(int child : children[nod])
{
for(int i=1;(1<<i)<=n;i++)
up[i][child]=up[i-1][up[i-1][child]];
DFS(child);
}
}
int LCA(int a, int b)
{
if(depth[a]<depth[b])
swap(a,b);
int k=depth[a]-depth[b];
for(int i=lg[k];i>=0;i--)
if(k&(1<<i))
a=up[i][a];
if(a==b)
return a;
for(int i=lg[depth[a]];i>=0;i--)
if(up[i][a]!=up[i][b])
{
a=up[i][a];
b=up[i][b];
}
return up[0][a];
}
int main()
{
lg[1]=0;
for(int i=2;i<MAX;i++)
lg[i]=lg[i>>1]+1;
fin >> n >> m;
for(int nod=2;nod<=n;nod++)
{
fin >> up[0][nod];
children[up[0][nod]].push_back(nod);
}
DFS(1);
while(m--)
{
int a,b;
fin >> a >> b;
fout << LCA(a,b) << '\n';
}
return 0;
}