Cod sursa(job #2255729)

Utilizator flibiaVisanu Cristian flibia Data 7 octombrie 2018 15:03:48
Problema Lowest Common Ancestor Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.07 kb
#include <bits/stdc++.h>
#define ll long long

using namespace std;

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

int n, m, x, y, st[200100], vf, lvl[100100], ap[100100], rmq[22][200100];
bool viz[100100];
vector <int> v[100100];

void dfs(int from, int niv){
	viz[from] = 1;
	lvl[from] = niv;
	ap[from] = ++vf;
	st[vf] = from;
	for(auto to : v[from])
		if(!viz[to]){
			dfs(to, niv + 1);
			st[++vf] = from;
		}		
}

int main(){
	in >> n >> m;
	for(int i = 2; i <= n; i++){
		in >> x;
		v[x].push_back(i);
	}
	dfs(1, 1);
	int sz = log2(vf);
	for(int i = 1; i <= vf; i++)
		rmq[0][i] = st[i];
	for(int p = 1; p <= sz; p++)
		for(int i = 1; i <= vf; i++)
			rmq[p][i] = (lvl[rmq[p - 1][i]] < lvl[rmq[p - 1][i + (1 << (p - 1))]] ? rmq[p - 1][i] : rmq[p - 1][i + (1 << (p - 1))]);
	while(m--){
		in >> x >> y;
		x = ap[x];
		y = ap[y];
		if(x > y)	
			swap(x, y);
		sz = log2(y - x + 1);
		out << (lvl[rmq[sz][x]] < lvl[rmq[sz][y - (1 << sz) + 1]] ? rmq[sz][x] : rmq[sz][y - (1 << sz) + 1]) << '\n';
	}
	return 0; 
}