Pagini recente » Cod sursa (job #602377) | Cod sursa (job #399216) | Cod sursa (job #1132282) | Cod sursa (job #2436317) | Cod sursa (job #2323996)
#include <bits/stdc++.h>
using namespace std ;
const int NMAX = 100001 ;
vector < int > v [ NMAX ] ;
ifstream f ("lca.in") ;
ofstream g ("lca.out") ;
void dfs ( int nod , int Father [ NMAX ] , int Level [ NMAX ] , int GR [ NMAX ] , int sqrtn )
{
Level [ nod ] = Level [ Father [ nod ] ] + 1 ; // adancimea nodului
// dfs va fi apelat in main din nodul 1
if ( Level [ nod ] < sqrtn ) // elementele din prima grupa
GR [ nod ] = 1 ;
else
{
if ( ! ( Level [ nod ] % sqrtn ) )
GR [ nod ] = Father [ nod ] ;
else
GR [ nod ] = GR [ Father [ nod ] ] ;
}
for( size_t i = 0 ; i < v [ nod ].size() ; ++ i )
dfs ( v [ nod ][ i ] , Father , Level , GR , sqrtn ) ;
}
int LCA ( int x , int y , int Father [ NMAX ] , int Level [ NMAX ] , int GR [ NMAX ] )
{
while ( GR [ x ] != GR [ y ] ) // cat timp nu sunt int aceeasi grupa
{ // avansam nodul inferior cu cate sqrt ( N ) pozitii ( o grupa )
if ( Level [ x ] > Level [ y ] )
x = GR [ x ] ;
else
y = GR [ y ] ;
}
while ( x != y ) // cand sunt in aceeasi grupa
{ // urcam " din tata in tata "
if ( Level [ x ] > Level [ y ] )
x = Father [ x ] ;
else
y = Father [ y ] ;
}
return x ;
}
int main ()
{
int Father [ NMAX ]= {0} , Level [ NMAX ] = {0} , GR [ NMAX ] ={0} ;
int n , q , i ; f >> n >> q ;
for ( i = 2 ; i <= n ; ++ i )
{
f >> Father [ i ] ;
v [ Father [ i ] ].push_back( i ) ;
}
dfs ( 1 , Father , Level , GR , sqrt ( n ) ) ;
//for ( i = 1 ; i <= n ; ++ i ) g << Father [ i ] << " " ;
//for ( i = 1 ; i <= n ; ++ i ) g << GR [ i ] << " " ;
//g << "\n" ;
//for ( i = 1 ; i <= n ; ++ i ) g << Level [ i ] << " " ;
while ( q -- )
{
int a , b ; f >> a >> b ;
g<< LCA ( a , b , Father , Level ,GR ) << "\n" ;
}
}