Cod sursa(job #3178830)

Utilizator Radu_MocanasuMocanasu Radu Radu_Mocanasu Data 2 decembrie 2023 16:10:29
Problema Lowest Common Ancestor Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.92 kb
#include <bits/stdc++.h>

using namespace std;
ifstream fin("lca.in");
ofstream fout("lca.out");
int n;
int t[100005][18];
int depth[100005];
void gent(){
    for(int j = 1; (1 << j) <= n; j++){
        for(int i = 1; i <= n; i++) t[i][j] = t[t[i][j - 1]][j - 1];
    }
}
int lca(int x, int y){
    if(depth[x] < depth[y]) swap(x,y);
    int d = depth[x] - depth[y];
    for(int i = 17; i >= 0; i--){
        if((1 << i) & d) x = t[x][i];
    }
    if(x == y) return x;
    for(int i = 17; i >= 0; i--){
        if(t[x][i] != t[y][i]){
            x = t[x][i];
            y = t[y][i];
        }
    }
    return t[x][0];
}
int main()
{
    int m,i,x,y;
    fin >> n >> m;
    t[1][0] = 1;
    for(i = 2; i <= n; i++){
        fin >> t[i][0];
        depth[i] = depth[t[i][0]] + 1;
    }
    for(i = 1; i <= m; i++){
        fin >> x >> y;
        fout << lca(x,y) << "\n";
    }
    return 0;
}