Cod sursa(job #3287909)

Utilizator AndreiMLCChesauan Andrei AndreiMLC Data 19 martie 2025 19:17:02
Problema Lowest Common Ancestor Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.23 kb
#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 && !q.empty() && !q2.empty())
	{
		int vf1 = q.front();
		int vf2 = q2.front();

		if (val[vf1] == nod2)
		{
			return vf1;
		}
		if (val[vf2] == nod1)
		{
			return vf2;
		}
		if(vf1 == vf2)
		{
			return vf1;
		}

		q.pop();
		q2.pop();

		for(auto it : G[vf1])
		{
			if (val[it] == nod2)
			{
				return it;
			}else if (val[it] != nod1)
			{
				val[it] = nod1;
				q.push(it);
			}
		}

		for (auto it : G[vf2])
		{
			if(val[it] == nod1)
			{
				return it;
			}
			else if (val[it] != nod2)
			{
				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';
	}
}