Cod sursa(job #2604829)

Utilizator mariaghinescu22Ghinescu Maria mariaghinescu22 Data 23 aprilie 2020 16:43:41
Problema Lowest Common Ancestor Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.27 kb
#include <iostream>
#include <fstream>

using namespace std;

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

const int N = 100001;
const int M = 100001;
const int L = 18;
int n, m, nr, time1, vf[N], urm[N], lst[N], t[L][N], tb[N], to[N]; 
// matricea t va tine al 2-lea stramos al lui j, t[i][j]

void add(int x, int y) {
	vf[++nr] = y;
	urm[nr] = lst[x];
	lst[x] = nr;
}

void dfs(int x) {
	tb[x] = ++time1; //timpul de intrare
	int y;
	for (int p = lst[x]; p != 0; p = urm[p]) {
		y = vf[p];
		if (tb[y] == 0) { // nu am mai fost pe acolo
			dfs(y);
			t[0][y] = x; //daca avem doar muchii, nu si vectorul de tati
		}
	}
	to[x] = ++time1; // timpul de iesire
}

int lca(int x, int y) {
	//caut liniar cel mai indepartat stramos al lui x care nu e stramos al lui y
	int pas = L - 1;
	int s;
	while (pas >= 0) {
		s = t[pas][x];
		if (s != 0 && ((tb[s] > tb[y]) || (to[s] < to[y]))) 
			x = s;
		pas--;
	}
	return t[0][x];
}

int main() {
	in >> n >> m;
	for (int i = 2; i <= n; i++) {
		int a;
		in >> a;
		add(a, i);
	}
	dfs(1);
	for (int i = 1; (1 << i) <= n; i++)
		for (int j = 1; j <= n; j++)
			t[i][j] = t[i - 1][t[i - 1][j]];
	for (int i = 1; i <= m; i++) {
		int x, y;
		in >> x >> y;
		out << lca(x, y) << '\n';
	}
	return 0;
}