Pagini recente » Istoria paginii runda/fmi-no-stress-4 | Cod sursa (job #1016931) | Concursul National de Soft Grigore Moisil Lugoj, Clasele 11-12 | Circulatie | Cod sursa (job #3287913)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
ifstream f("lca.in");
ofstream g("lca.out");
const int NMAX = 100005;
vector<int> G[NMAX];
int n;
int m;
int val[NMAX];
int bfs(int nod1, int nod2)
{
bool found = 0;
queue<int> q;
queue<int> q2;
q.push(nod1);
q2.push(nod2);
val[nod1] = nod1;
val[nod2] = nod2;
while (!found)
{
int vf1;
int vf2;
if (q.empty())
{
vf1 = 0;
}
else {
vf1 = q.front();
q.pop();
}
if (q2.empty())
{
vf2 = 0;
}
else {
vf2 = q2.front();
q2.pop();
}
if (val[vf1] == nod2)
{
return vf1;
}
if (val[vf2] == nod1)
{
return vf2;
}
if(vf1 == vf2)
{
return vf1;
}
for(auto it : G[vf1])
{
if (val[it] == nod2)
{
return it;
}else
{
val[it] = nod1;
q.push(it);
}
}
for (auto it : G[vf2])
{
if(val[it] == nod1)
{
return it;
}
else
{
val[it] = nod2;
q2.push(it);
}
}
}
}
int main()
{
f >> n >> m;
for(int i = 2;i<=n;i++)
{
int x;
f >> x;
if (i != 1)
{
G[i].push_back(x);
}
}
for (int i = 1; i <= m; i++)
{
int x, y;
f >> x >> y;
g << bfs(x, y) << '\n';
}
}