Pagini recente » Cod sursa (job #932746) | Cod sursa (job #1465128) | Cod sursa (job #1130693) | Cod sursa (job #3194446) | Cod sursa (job #458055)
Cod sursa(job #458055)
#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;
}