Cod sursa(job #2786682)

Utilizator TghicaGhica Tudor Tghica Data 21 octombrie 2021 15:08:43
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.35 kb
#include <fstream>

using namespace std;

int par[100001], s[100001][25], h[100001];

int FindRuda( int x, int h ) {
    if( h == 0 )
        return x;
    int put = 1;
    while( ( 1 << put ) <= h ) {
        put++;
    }
    put--;
    return FindRuda( s[x][put], h - ( 1 << put ) );
}

int main() {
    ifstream cin("lca.in");
    ofstream cout("lca.out");
    int n, m, i, j, a, b, put2, x, y, last;
    cin>>n>>m;
    h[1] = 0;
    for( i = 2; i <= n; i++ ) {
        cin>>a;
        h[i] = h[a] + 1;
        s[i][0] = a;
    }
    s[1][1] = 0;
    i = 1;
    while( ( 1 << i ) <= n ) {
        for( j = 1; j <= n; j++ ) {
            s[j][i] = s[s[j][i - 1]][i - 1];
        }
        i++;
    }
    while( m-- ) {
      cin>>a>>b;
      if( h[a] < h[b] ){
          b = FindRuda( b, h[b] - h[a] );
      }
      else {
          a = FindRuda( a, h[a] - h[b] );
      }
      put2 = 1;
      while( put2 <= h[a] ) {
        put2 *= 2;
      }
      put2 /= 2;
      if( a == b )  {
        cout<<a<<"\n";
        continue;
      }
      while( put2 != 0 ) {
          x = FindRuda( a, put2 );
          y = FindRuda( b, put2 );
          if( x == y ) {
            last = x;
          } else {
            a = x;
            b = y;
          }
          put2 /= 2;
      }
    cout<<last<<"\n";
  }
return 0;
}