Pagini recente » Cod sursa (job #1663449) | Cod sursa (job #227396) | Cod sursa (job #1926033) | Cod sursa (job #1572176) | Cod sursa (job #461732)
Cod sursa(job #461732)
#include <vector>
#include <cstdlib>
#include <fstream>
#define Nmax 100011
/*
*
*/
using namespace std;
int levelmax;
int f[Nmax], f2[Nmax], lev[Nmax];
vector< int > G[Nmax];
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;
f[1]=1;
for( i=2; i <= N; ++i )
{
in>>f[i];
G[f[i]].push_back(i);
}
GetLevMax( 1, 0 );
DFS( 1, 1 );
ofstream out( "lca.out" );
for( ; M; --M )
{
in>>x>>y;
out<<LCA( x, y )<<'\n';
}
return EXIT_SUCCESS;
}