Cod sursa(job #3137094)

Utilizator SerbanCaroleSerban Carole SerbanCarole Data 11 iunie 2023 11:35:39
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.15 kb
#include <fstream>
#include <vector>
#include <algorithm>
#define int long long
using namespace std;

const int MAX = 1e5 + 1;

ifstream cin("lca.in");
ofstream cout("lca.out");

vector <int> g[MAX];

int n , x , q , y , bbl[19][MAX] , tin[MAX] , tout[MAX] , tm;

void dfs( int x , int t ){

    bbl[0][x] = t;

    for(int i = 1 ; i <= 18 ; i++){

        bbl[i][x] = bbl[i-1][bbl[i-1][x]];
    }

    tin[x] = ++tm;

    for(auto it : g[x]){

        dfs(it,x);
    }

    tout[x] = ++tm;

}

bool ispapa( int &x , int &t ){

    return(tin[t]<=tin[x]&&tout[x]<=tout[t]);
}

signed main()
{

    cin >> n >> q;

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

        cin >> x;
        g[x].push_back(i);
    }

    dfs(1,0);

    while(q--){

        cin >> x >> y;

        if(!ispapa(y,x)){

            int step = 18;

            while(step >= 0){

                if(bbl[step][x] && !ispapa(y,bbl[step][x])){

                    x = bbl[step][x];
                }

                step--;
            }
        }

        if(!ispapa(y,x)) x = bbl[0][x];

        cout << x << '\n';
    }

    return 0;
}