Pagini recente » Cod sursa (job #1026113) | Cod sursa (job #1465975) | Calibrare limite de timp | Cod sursa (job #1252435) | Cod sursa (job #1667434)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <bitset>
using namespace std;
const int NMAX = 100001;
int father[NMAX+1];
queue<int> coada;
vector<int> muchii[NMAX];
int n,m;
bitset<NMAX> mark;
int high[NMAX];
void citire()
{
scanf("%d %d",&n,&m);
for(int i=1;i<n;i++)
{
scanf("%d",&father[i+1]);
muchii[father[i+1]].push_back(i+1);
}
}
void bfs()
{
mark.set(1);
coada.push(1);
int y;
while(!coada.empty())
{
y = coada.front();
for(unsigned int i=0;i<muchii[y].size();i++)
if(!mark.test(muchii[y][i]))
{
high[muchii[y][i]] = high[y] + 1;
mark.set(muchii[y][i]);
coada.push(muchii[y][i]);
}
coada.pop();
}
}
int main()
{
freopen("lca.in","r",stdin);
freopen("lca.out","w",stdout);
citire();
bfs();
int x,y;
for(int i=1;i<=m;i++)
{
scanf("%d %d",&x,&y);
if(high[x] > high[y])
{
while(high[x] != high[y])
x = father[x];
}
else
if(high[y] > high[x])
{
while(high[y] != high[x])
y = father[y];
}
while(x!=y)
{
x = father[x];
y = father[y];
}
printf("%d\n",x);
}
fclose(stdin);
fclose(stdout);
return 0;
}