Pagini recente » Cod sursa (job #772245) | Cod sursa (job #1646351) | Cod sursa (job #405612) | Cod sursa (job #2212956) | Cod sursa (job #2358749)
#include <iostream>
#include <vector>
#include <queue>
#include <fstream>
using namespace std;
ifstream fin("lca.in");
ofstream fout("lca.out");
#define NMAX 100001
int n, m, p;
unsigned short int ve[NMAX];
queue <unsigned short int> v[NMAX];
unsigned short int etaj[NMAX], etaje[NMAX];
void citire()
{
fin>>n>>m;
for(int i=2; i<=n; i++)
{
int x;
fin>>x;
v[x].push(i);
etaj[i]=etaj[x]+1;
}
}
void euler(int k)
{
p++; ve[p]=k; etaje[p]=etaj[k];
while(!v[k].empty())
{
euler(v[k].front());
v[k].pop();
p++; ve[p]=k;
etaje[p]=etaj[k];
}
}
int Find(int nr)
{
int poz=1;
while(nr!=ve[poz])
poz++;
return poz;
}
void rezolva()
{
int x, y;
int fx, fy;
fin>>x>>y;
fx=Find(x);
fy=Find(y);
//fout<<fx<<" "<<fy<<'\n';
int _min=n+5;
int val=0;
for(int i=min(fx, fy); i<=max(fx, fy); i++)
{
if(_min>etaje[i]) _min=etaje[i], val=i;
}
fout<<ve[val]<<'\n';
}
int main()
{
citire();
euler(1);
/*for(int i=1; i<=p; i++)
fout<<ve[i]<<" ";
fout<<'\n';
for(int i=1; i<=p; i++)
fout<<etaje[i]<<" ";*/
for(int i=1; i<=m; i++)
rezolva();
return 0;
}