Pagini recente » Cod sursa (job #2885485) | Cod sursa (job #784640) | Rating Seulean Erik-Cristian (blexx) | Cod sursa (job #557640) | Cod sursa (job #461736)
Cod sursa(job #461736)
#include <vector>
#include <cstdlib>
#include <fstream>
#define Nmax 100011
#define SIZE 200003
/*
*
*/
using namespace std;
ifstream in( "lca.in" );
int levelmax, idx;
char file[SIZE];
int f[Nmax], f2[Nmax], lev[Nmax];
vector< int > G[Nmax];
inline void read( int& x )
{
while( file[idx] < '0' || file[idx] > '9' )
if( ++idx == SIZE )
{
idx=0;
in.read( file, SIZE );
}
for( x=0; file[idx] >= '0' && file[idx] <= '9'; )
{
x=x*10+file[idx]-'0';
if( ++idx == SIZE )
{
idx=0;
in.read( file, SIZE );
}
}
}
inline void GetLevMax( int x, int level )
{
lev[x]=level;
if( G[x].empty() )
{
levelmax=( level >= levelmax ? level : levelmax );
return;
}
vector< int >::const_iterator it=G[x].begin(), iend=G[x].end();
for( ; it < iend; ++it )
GetLevMax( *it, level+1 );
}
inline void DFS( int x, int fx )
{
f2[x]=fx;
if( 0 == lev[x]%levelmax )
fx=x;
if( G[x].empty() )
return;
vector< int >::const_iterator it=G[x].begin(), iend=G[x].end();
for( ; it < iend; ++it )
DFS( *it, fx );
}
inline int LCA( int x, int y )
{
while( f2[x] != f2[y] )
if( lev[x] >= lev[y] )
x=f2[x];
else y=f2[y];
while( x != y )
if( lev[x] >= lev[y] )
x=f[x];
else y=f[y];
return x;
}
int main( void )
{
int N, M, i, x, y;
// ifstream in( "lca.in" );
// in>>N>>M;
read(N); read(M);
f[1]=1;
for( i=2; i <= N; ++i )
{
// in>>f[i];
read(f[i]);
G[f[i]].push_back(i);
}
GetLevMax( 1, 0 );
DFS( 1, 1 );
ofstream out( "lca.out" );
for( ; M; --M )
{
//in>>x>>y;
read(x); read(y);
out<<LCA( x, y )<<'\n';
}
return EXIT_SUCCESS;
}