Cod sursa(job #2860585)

Utilizator alextmAlexandru Toma alextm Data 2 martie 2022 20:04:51
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.95 kb
#include <bits/stdc++.h>
using namespace std;

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

const int MAXN = 1e5 + 5;
const int MAXLOG = 18;

vector<int> G[MAXN];
int tin[MAXN], tout[MAXN];
int timer, anc[MAXN][20];

inline void dfs(int node, int parent = 1) {
	tin[node] = ++timer;
	anc[node][0] = parent;
	for(int i = 1; i <= MAXLOG; i++)
		anc[node][i] = anc[ anc[node][i-1] ][i-1];
		
	for(int son : G[node])
		if(son != parent)
			dfs(son, node);
	
	tout[node] = ++timer;
}

bool isAncestor(int x, int y) {
	return (tin[x] <= tin[y] && tout[y] <= tout[x]);
}

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

int main() {
	int n, q, x, y;
	fin >> n >> q;
	
	for(int i = 2; i <= n; i++) {
		fin >> x;
		G[x].push_back(i);
	}
	
	dfs(1);
	
	while(q--) {
		fin >> x >> y;
		fout << LCA(x, y) << '\n';
	}
	
	return 0;
}