Cod sursa(job #2360729)

Utilizator CryshanaGanea Carina Cryshana Data 2 martie 2019 09:29:12
Problema Lowest Common Ancestor Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.62 kb
#include <iostream>

#include <fstream>

#include <vector>

using namespace std;



ifstream  fin ("lca.in" );

ofstream fout ("lca.out");



const int N = 100001, L = 21;

int log[L], r[L][2*N], e[2*N], ne, nivel[N], poz[N];



vector <int> fii[N];



void dfs ( int x )

{

    e[++ne] = x;

    poz[x] = ne;

    for ( auto y : fii[x])

    {

        nivel[y] = 1 + nivel[x];

        dfs(y);

        e[++ne] = x;

    }

}



int main()

{

    int n, m;

    fin >> n >> m;

    for ( int i = 2; i <= n; i++ )

    {

        int x;

        fin >> x;

        fii[x].push_back (i);

    }

    dfs (1);

    for ( int i = 2; i <= ne; i++ )

    {

        log[i] = log[i/2] + 1;

    }

    for ( int j = 1; j <= ne; j ++ )

    {

        r[0][j] = e[j];

    }

    for ( int i = 1; i <= log[ne]; i++ )

    {

        for ( int j = 1 << i; j <= ne; j++ )

        {

            int st, dr;

            st = r[i-1][j - ( 1 << ( i-1 ) )];

            dr = r[i-1][j];

            if ( nivel [st] <= nivel[dr] )

            {

                r[i][j] = st;

            }

            else

            {

                r[i][j] = dr;

            }

        }

    }

    while ( m != 0 )

    {

        int x, y;

        m--;

        fin >> x >> y;

        if ( poz[x] > poz[y] )

        {

            x += y;

            y = x - y;

            x = x - y;

        }

        int lung = poz[y] - poz[x] + 1;

        int l = log[lung];

        if ( nivel[r[l][poz[y]]] < nivel [r[l][poz[x] + (1 << l )]])

        fout << r[l][poz[y]] << "\n";

        else

        fout << r[l][poz[x] + (1 <<l)] << "\n";

    }

    return 0;

}