Cod sursa(job #2786614)

Utilizator BlueLuca888Girbovan Robert Luca BlueLuca888 Data 21 octombrie 2021 12:05:10
Problema Lowest Common Ancestor Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.27 kb
#include <bits/stdc++.h>

using namespace std;

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

int level[100005];
int dp[18][100005];
int n, q, x, y, stramos_x, stramos_y, sol;
int st, up, dr;

int stramos(int nod, int dist){
    int p2=0;
    while(dist > 0){
        if(dist&1)
            nod = dp[p2][nod];
        p2++;
        dist >>= 1;
    }

    return nod;
}

int main (){
    fin>>n>>q;

    dp[0][1]=0; level[1]=1;
    for(int i=2; i<=n; i++){
        fin>>dp[0][i];
        level[i] = level[ dp[0][i] ] + 1;
    }

    for(int i=1; i<=17; i++)
        for(int j=1; j<=n; j++)
            dp[i][j] = dp[i-1][ dp[i-1][j] ];

    while(q--){
        fin>>x>>y;

        if(level[x] > level[y])
            swap(x, y);

        x = stramos(x, level[y] - level[x]);

        if(x == y){
            fout<<x<<"\n";
            continue;
        }

        st=1;
        dr=level[x]-1;
        while(st <= dr){
            up=(dr-st)/2+st;

            stramos_x = stramos(x, up);
            stramos_y = stramos(y, up);

            if(stramos_x == stramos_y){
                sol=stramos_x;
                dr=up-1;
            }else
                st=up+1;
        }

        fout<<sol<<"\n";
    }
    return 0;
}