Cod sursa(job #461732)

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