Cod sursa(job #871168)

Utilizator fhandreiAndrei Hareza fhandrei Data 4 februarie 2013 15:48:00
Problema Lowest Common Ancestor Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 1.03 kb
// Include
#include <fstream>
#include <algorithm>
#include <vector>
using namespace std;

// Definitii
#define pb push_back

// Constante
const int sz = (int)1e5+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];

// Main
int main()
{
	in >> nodes >> questions;
	for(int i=2 ; i<=nodes ; ++i)
	{
		in >> father[i];
		graph[father[i]].pb(i);
	}
	dfs(1);
	
	vector<int>::iterator beg = euler.begin();
	while(questions--)
	{
		int node1, node2;
		
		in >> node1 >> node2;
		if(pos[node2] < pos[node1])
			swap(node1, node2);
		out << *min_element(beg+pos[node1], beg+pos[node2]) << '\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);
	}
}