Pagini recente » Istoria paginii runda/valicaroom1 | Istoria paginii runda/usor_dar_greu | Cod sursa (job #155488) | Cod sursa (job #1236876) | Cod sursa (job #1667040)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <bitset>
using namespace std;
ifstream in("lca.in");
ofstream out("lca.out");
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()
{
in>>n>>m;
for(int i=1;i<n;i++)
{
in>>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()
{
citire();
bfs();
int x,y;
for(int i=1;i<=m;i++)
{
in>>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];
}
out<<x<<"\n";
}
in.close();
out.close();
return 0;
}