Cod sursa(job #2324223)

Utilizator Andrei-27Arhire Andrei Andrei-27 Data 20 ianuarie 2019 14:06:56
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.98 kb
#include <bits/stdc++.h>
using namespace std;
ifstream f ("lca.in") ;
ofstream g ("lca.out") ;
const int NMAX = 100001 ;
const int LOGNMAX = 20 ;

vector <  int > v [ NMAX ] ;

int Father [ NMAX ] ,  Level [ NMAX ]  , rmq_father [ LOGNMAX][ NMAX ] , n ;

    void dfs ( int nod , int father )
    {
        Level [ nod ] = Level [ father ] + 1 ;
        for ( size_t i = 0 ; i < v[  nod ].size() ; ++ i )
        {
            dfs ( v [ nod ][ i ] , nod  ) ;
        }
    }

    int query ( int x , int y )
    {
        int log , i ;
        if ( Level [ x ] > Level [ y ] )    swap ( x , y ) ;

        for ( log = 0 ; ( 1 << log ) <= Level [ y ] ; log ++ ) ;

        for (  i = log ; i >= 0 ; -- i )
        {
            if ( Level [ y ] - ( 1 << i ) >= Level [ x ] )    // practic ia fiecare bit al distantei
            y = rmq_father [ i ][ y ] ;                       //  level [ x ] - level [ y ] + 1
        }
        if ( x == y )   return x ;

        for (  i = log ; i >= 0 ; -- i )
        if ( rmq_father [ i ][ x ] != rmq_father [ i ][ y ] )
        {
            x = rmq_father [ i ][ x ] ;
            y = rmq_father [ i ][ y ] ;
        }
        return Father [ x ] ;
    }

int rmq (  )
{
    int i , j ;
    for ( i = 1 ; i <= n ; ++ i )
    {
        rmq_father [ 0 ][ i ] = Father [ i ] ;
    }
    //rmq_edge [ i ][ j ] - muchia de cost minim dintre nodul j
    // si al 2 ^ i stramos al nodului j
    for ( i = 1 ; ( 1 << i ) <= n ; ++ i )
    for ( j = 1 ; j <= n ; ++ j )
    {
        rmq_father [ i ][ j ] = rmq_father [ i - 1 ][ rmq_father [ i - 1 ][ j ] ] ;
    }
}



int main ()
{
    int q , i ; f >> n >> q ;
    for ( i = 2 ; i <= n ; ++ i )
        {

            f >> Father [ i ] ;
            v [ Father [ i ] ].push_back( i ) ;
        }
        dfs ( 1 , 0 ) ;
        rmq(  ) ;
        while ( q -- )
        {
            int x , y ; f >> x >> y ;
           g << query ( x , y ) << "\n" ;
        }

}