Cod sursa(job #3170852)

Utilizator samyro14Samy Dragos samyro14 Data 18 noiembrie 2023 10:47:25
Problema Lowest Common Ancestor Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.64 kb
#include <bits/stdc++.h>
using namespace std;

ifstream fin("lca.in");
ofstream fout("lca.out");
const int maxn = 1e5 + 2;

set<int> s;
int t[maxn], n, m, timer;
vector<int> a[maxn + 2];
int nivel[maxn + 2];
int poz[maxn + 2];
int e[2 * maxn + 2];
int lg[100005];
int r[20][2 * maxn];
void read(){
   fin >> n >> m;
   t[1] = 1;
   for(int i = 2; i <= n; ++i){
      int x; fin >> x;
      t[i] = x;
      a[x].push_back(i);
   }
}
void dfs(int i){
    nivel[i] = nivel[t[i]] + 1;
    e[++timer] = i;
    poz[i] = timer;
    for(auto x : a[i]){
        dfs(x);
        e[++timer] = i;
    }
}
void precalculate(){
    lg[0] = -1;
    for(int i = 1; i <= timer; ++i){
        lg[i] = lg[i >> 1] + 1;
        r[0][i] = e[i];
    }
    for(int i = 1; (1 << i) <= timer; ++i){
        for(int j = (1 << i); j <= timer; ++j){
                r[i][j] = r[i - 1][j];
                if(nivel[r[i - 1][j - (1 << (i - 1))]] < nivel[r[i - 1][j]])
                    r[i][j] = r[i - 1][j - (1 << (i - 1))];
        }
    }
} 
int lca(int x, int y){
    int left = poz[x];
    int right = poz[y];
    if(left > right)
        swap(left, right);
    int len = lg[right - left + 1];
    x = r[len][left + (1 << len)];
    y = r[len][right];
    if(nivel[y] < nivel[x])
        x = y;

    return x;
}
int main(){
    read();
    dfs(1);
    precalculate();
    for(int i = 1; i <= m; ++i){
        int x, y;
        fin >> x >> y;
        fout << lca(x, y) << "\n";
    }
    return 0;
}
/*
r[i][j] = nodul care se afla pe nivelul minim in arbore, din secventa de lungime 2^i si care se termina
pe pozitia j
    
*/