Cod sursa(job #2857875)

Utilizator Andrei_Tud1Andrei Tudorache Andrei_Tud1 Data 26 februarie 2022 15:27:30
Problema Lowest Common Ancestor Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.48 kb
#include <fstream>
#include <iostream>
#include <vector>
#define DIM 100010

using namespace std;
ifstream fin("lca.in");
ofstream fout("lca.out");

vector<int> L[DIM];
int E[2*DIM], N[2*DIM], F[DIM], lg[2*DIM];
int D[19][2*DIM];

int n, m, k, x, y, z, j;

void euler(int nod, int niv)
{
    E[++k] = nod;
    N[k] = niv;
    F[nod] = k;
    for(int i = 0; i < L[nod].size(); i++)
    {
        euler(L[nod][i], niv + 1);
        E[++k] = nod;
        N[k] = niv;
    }
}

int main()
{
    int i;
    fin >> n >> m;
    for(i = 2; i <= n; i++)
    {
        fin >> x;
        L[x].push_back(i);
    }

    euler(1, 1);

    lg[1] = 0;
    for(i = 2; i <= k; i++)
        lg[i] = lg[i / 2] + 1;

    for(i = 1; i <= k; i++)
        D[0][i] = E[i];

    for(i = 1; (1 << i) <= k; i++)
    {
        for(j = 1; j + (1 << i) - 1 <= k; j++)
        {
            int min1 = D[i-1][j];
            if(N[min1] > N[ D[i-1][j + (1 << (i-1))] ])
                min1 = D[i-1][j + (1 << (i-1))];
            D[i][j] = min1;
        }
    }

    for(i = 1; i <= m; i++)
    {
        fin >> x >> y;
        x = F[x];
        y = F[y];

        if (x > y)
        {
            int aux = x;
            x = y;
            y = aux;
        }

        z = lg[y - x + 1];
        int rasp = D[z][x];
        if(N[rasp] > N[ D[z][y - (1 << z) + 1] ] );
            rasp = D[z][y - (1 << z) + 1];

        fout << rasp << endl;
    }
    return 0;
}