Cod sursa(job #458055)

Utilizator alexandru92alexandru alexandru92 Data 22 mai 2010 19:26:18
Problema Lowest Common Ancestor Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 0.67 kb
#include <vector>
#include <cstdlib>
#include <fstream>
#include <algorithm>
#define Nmax 100111

/*
 * 
 */
using namespace std;
int N;
int f[Nmax], was[Nmax];
inline int solve( int x, int y )
{
	fill( was, was+N+1, false );
	for( ; x != f[x] || y != f[y]; x=f[x], y=f[y] )
	{
		if( x != f[x] )
		{
			if( 2 == was[x] )
				return x;
			was[x]=1;
		}
		if( y != f[y] )
		{
			if( 1 == was[y] )
				return y;
			was[y]=2;
		}
	}
	return x;
}
int main( void )
{
	int M, i, x, y;
	ifstream in( "lca.in" );
	ofstream out( "lca.out" );
	in>>N>>M;
	f[1]=1;
	for( i=2; i <= N; ++i )
		in>>f[i];
	for( ; M; --M )
	{
		in>>x>>y;
		out<<solve( x, y )<<"\n";
	}
	return EXIT_SUCCESS;
}