Cod sursa(job #461565)

Utilizator BitOneSAlexandru BitOne Data 7 iunie 2010 16:32:27
Problema Lowest Common Ancestor Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 1.48 kb
#include <cstdlib>
#include <fstream>
#include <iterator>
#define Modulo 6660023

/*
 *
 */
using namespace std;
int f[ 100011 ];
struct list
{
    int x, y, lca;
    list* next;
    list( int _x=0, int _y=0, int _lca=0, list* _next=NULL ) : x(_x), y(_y), lca(_lca), next(_next) {}
} *v[Modulo];
inline void Add( int x, int y, int lca, int p )
{
    list* pp=new list( x, y, lca, v[p] );
    v[p]=pp;
}
inline int LCA( int x, int y, int p )
{
    list* pp;
    for( pp=v[p]; NULL != pp && ( x != pp->x || y != pp->y ) ; pp=pp->next );
    if( pp )
        return pp->lca;
    int _x, _y;
    int was[100011]={0};
    for( _x=x, _y=y; _x != f[_x] || _y != f[_y]; _x=f[_x], _y=f[_y] )
    {
        if( _x != f[_x] )
        {
            if( 2 == was[_x] )
            {
                Add( x, y, _x, p );
                return _x;
            }
            was[_x]=1;
        }
        if( _y != f[_y] )
        {
            if( 1 == was[_y] )
            {
                Add( x, y, _y, p );
                return _y;
            }
            was[_y]=2;
        }
    }
    Add( x, y, _x, p );
    return 1;
}
int main( void )
{
    int N, M, x, y;
    ifstream in( "lca.in" );
    ofstream out( "lca.out" );
    if( !in )
        return 1;
    in>>N>>M;
    f[1]=1;
    for( x=2; x <= N; ++x )
        in>>f[x];
    for( ; M; --M )
    {
        in>>x>>y;
        out<<LCA( x, y, (x*500+y)%Modulo  )<<'\n';
    }
    return EXIT_SUCCESS;
}