Cod sursa(job #2115941)

Utilizator calinfloreaCalin Florea calinflorea Data 27 ianuarie 2018 11:28:27
Problema Lowest Common Ancestor Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.6 kb
#include <bits/stdc++.h>

using namespace std;
ifstream fin ("lca.in");
ofstream fout ("lca.out");
const int Nmax = 100005;
const short Pmax = 22;
int rmq[Pmax][4 * Nmax] , E[20 * Nmax] , niv[20 * Nmax] , poz[Nmax];
int n , Q , a[Nmax] , p2[Nmax] , dim;
vector < int > L[Nmax];
inline void Read()
{
    int x;
    fin >> n >> Q;
    for(int i = 2 ; i <= n ; i++)
    {
        fin >> x;
        L[x] . push_back(i);
    }
}
void DFS(int varf , int nivel)
{
    ++dim;
    E[dim] = varf;
    niv[dim] = nivel;
    poz[varf] = dim;
    for(auto i : L[varf])
    {
        DFS(i , nivel + 1);
        ++dim;
        E[dim] = varf;
        niv[dim] = nivel;
    }
}
inline void Build_RMQ()
{
    int N , x , y;
    p2[1] = 0;
    for(int i = 2 ; i <= dim ; i++)
        p2[i] = p2[i / 2] + 1;
    for(int i = 1 ; i <= dim ; i++)
        rmq[0][i] = i;
    N = p2[dim];
    for(int i = 1 ; i <= N ; i++)
        for(int j = 1 ; j <= dim - (1 << i) + 1 ; j++)
    {
        x = niv[rmq[i - 1][j]];
        y = niv[rmq[i - 1][j + (1 << (i - 1))]];
        if(x < y)
            rmq[i][j] = rmq[i - 1][j];
        else rmq[i][j] = rmq[i - 1][j + (1 << (i - 1))];
    }
}
int main()
{
    int x , y , L , t , t1;
    Read();
    DFS(1 , 0);
    Build_RMQ();
    while(Q--)
    {
        fin >> x >> y;
        x = poz[x];
        y = poz[y];
        if(x > y)
            swap(x , y);
        L = p2[y - x + 1];
        t = rmq[L][x];
        t1 = rmq[L][y - (1 << L) + 1];
        fout << min(E[t] , E[t1]) << "\n";
    }
    fin.close();
    fout.close();
    return 0;
}