Cod sursa(job #461736)

Utilizator BitOneSAlexandru BitOne Data 8 iunie 2010 14:39:00
Problema Lowest Common Ancestor Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.92 kb
#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;
}