Cod sursa(job #873841)

Utilizator fhandreiAndrei Hareza fhandrei Data 7 februarie 2013 18:03:33
Problema Lowest Common Ancestor Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.48 kb
// Include
#include <fstream>
#include <algorithm>
#include <vector>
using namespace std;

// Definitii
#define pb push_back

// Constante
const int sz = (int)1e5+1;
const int oo = (1<<30)-1;

// Functii
void dfs(int node);

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

int nodes, questions;
int father[sz];
vector<int> euler;
vector<int> graph[sz];

int pos[sz];

int leftRange, rightRange;

int rmq[21][sz*4];
int lg[sz*4];

// Main
int main()
{
	in >> nodes >> questions;
	for(int i=2 ; i<=nodes ; ++i)
	{
		in >> father[i];
		graph[father[i]].pb(i);
	}
	dfs(1);
	
	int limit = euler.size();
	rmq[0][1] = euler[0];
	for(int i=2 ; i<=limit ; ++i)
	{
		lg[i] = lg[i/2] + 1;
		rmq[0][i] = euler[i-1];
	}
	
	for(int i=1 ; (1<<i)<=limit ; ++i)
		for(int j=1 ; j<=limit-(1<<i)+1 ; ++j)
			rmq[i][j] = min(rmq[i-1][j], rmq[i-1][j+(1<<i-1)]);
	
	while(questions--)
	{
		int node1, node2;
		
		in >> node1 >> node2;
		if(pos[node2] < pos[node1])
			swap(node1, node2);
		
		leftRange = pos[node1]+1;
		rightRange = pos[node2]+1;
		
		int dif = rightRange-leftRange + 1;
		int log = lg[dif];
		out << min(rmq[log][leftRange], rmq[log][rightRange-(1<<log)+1]) << '\n';
	}
	
	in.close();
	out.close();
	return 0;
}

void dfs(int node)
{
	euler.pb(node);
	pos[node] = euler.size() - 1;
	
	vector<int>::iterator it, end=graph[node].end();
	for(it=graph[node].begin() ; it!=end ; ++it)
	{
		dfs(*it);
		euler.pb(node);
	}
}