Cod sursa(job #458058)

Utilizator alexandru92alexandru alexandru92 Data 22 mai 2010 19:34:49
Problema Lowest Common Ancestor Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 1.13 kb
#include <vector>
#include <cstdlib>
#include <cstdio>
#include <algorithm>
#define SIZE 900001
#define Nmax 100111

/*
 * 
 */
using namespace std;
//ifstream in( "lca.in" );
//ofstream out( "lca.out" );
int N, idx, s=sizeof( char );
char file[SIZE];
int f[Nmax], was[Nmax];
inline void read( int& x )
{
	while( file[idx] < '0' || file[idx] > '9' )
		if( ++idx == SIZE )
		{
			idx=0;
			fread( file, s,  SIZE, stdin );
		}
	for( x=0; file[idx] >= '0' && file[idx] <= '9'; )
	{
		x=x*10+file[idx]-'0';
		if( ++idx == SIZE )
		{
			idx=0;
			fread( file, s, SIZE, stdin );
		}
	}
}
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 )
{
	freopen( "lca.in", "rt", stdin );
	freopen( "lca.out", "wt", stdout );
	int M, i, x, y;
	read(N); read(M);
	f[1]=1;
	for( i=2; i <= N; ++i )
		read( f[i] );
	for( ; M; --M )
	{
		read( x ); read( y );
		printf( "%d\n", solve( x, y ) );
	}
	return EXIT_SUCCESS;
}