Cod sursa(job #3378297)

Utilizator batasAndrei Batis batas Data 25 noiembrie 2026 19:30:16
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.5 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <cmath>
using namespace std;
using VI = vector<int>;
using VVI = vector<VI>;

ifstream fin("lca.in");
ofstream fout("lca.out");

int n, m;
int timer, Log;
VI tin, tout;
VVI adj, anc;

void ReadInput();
void Preprocess(int root);
void Solve();
int LCA(int x, int y);
void DFS(int node, int fa);
bool IsAncestor(int x, int y);

int main()
{
	ReadInput();
	Solve();
	
	return 0;
}

void Solve()
{
	Preprocess(1);

	int x, y;
	while (m--)
	{
		fin >> x >> y;
		
		fout << LCA(x, y) << '\n';
	}
}

void DFS(int node, int fa)
{
	tin[node] = ++timer;
	
	anc[0][node] = fa;
	for (int i = 1; i <= Log; ++i)
		anc[i][node] = anc[i - 1][anc[i - 1][node]];
		
	for (int nbr : adj[node])
		if (nbr != fa)
			DFS(nbr, node);
			
	tout[node] = ++timer;
}

int LCA(int x, int y)
{
	if (IsAncestor(x, y)) return x;
	if (IsAncestor(y, x)) return y;
	
	for (int i = Log; i >= 0; --i)
		if (!IsAncestor(anc[i][x], y))
			x = anc[i][x];
			
	return anc[0][x];
}

bool IsAncestor(int x, int y)
{
	if (tin[x] <= tin[y] && tout[x] >= tout[y])
		return true;
		
	return false;
}

void Preprocess(int root)
{
	Log = ceil(log2(n));
	anc = VVI(Log + 1, VI(n + 1));
	DFS(root, root);
}

void ReadInput()
{
	fin >> n >> m;
	
	tin = tout = VI(n + 1);
	adj = VVI(n + 1);
	
	int node;
	for (int i = 1; i < n; ++i)
	{
		fin >> node;
		
		adj[node].push_back(i + 1);
		adj[i + 1].push_back(node);
	}	
}