Cod sursa(job #3002767)

Utilizator robertanechita1Roberta Nechita robertanechita1 Data 15 martie 2023 09:42:56
Problema Lowest Common Ancestor Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.61 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin("sortaret.in");
ofstream fout("sortaret.out");

int n, m, st[200005], nivel[200005], poz[100005], pow_2[200005], p, rmq[22][200005];
vector<int>g[100005];

void Euler(int nod, int niv){
    st[++p] = nod;
    nivel[p] = niv;
    poz[nod] = p;
    for(auto i : g[nod]){
        Euler(i, niv + 1);
        st[++p] = nod;
        nivel[p] = niv;
    }
}

void Rmq(){
//    cout << p << " ";
    for(int i = 1; i <= p; i++)
        rmq[0][i] = i;
    for(int i = 1; (1 << i) <= p; i++)
        for(int j = 1; j + (1 << i) - 1 <= p; j++){
            if(nivel[rmq[i-1][j]] < nivel[rmq[i-1][j + (1 << (i-1))]]){
                rmq[i][j] = rmq[i - 1][j];
            }
            else{
                rmq[i][j] = rmq[i - 1][j + (1 << (i-1))];
            }
//            cout << i << " " << j << " " << rmq[i][j] << " ";
        }

}

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

    Euler(1, 0);

    pow_2[1] = 0;
    for (int i = 2; i <= p; i++) {
        pow_2[i] = 1 + pow_2[i / 2];
//        if (p == 16)
//            cout << i << " ";
    }


    Rmq();
    for(int i = 1; i <= m; i++){
        fin >> x >> y;
        x = poz[x];
        y = poz[y];
        if(x > y)
            swap(x, y);
        int lg = pow_2[y - x + 1];
        if(nivel[rmq[lg][x]] < nivel[rmq[lg][y - (1 << lg) + 1]])
            fout << st[rmq[lg][x]] << "\n";
        else fout << st[rmq[lg][y - (1 << lg) + 1]] << "\n";
    }

    return 0;
}