Cod sursa(job #2576005)

Utilizator IoanaDraganescuIoana Draganescu IoanaDraganescu Data 6 martie 2020 16:41:44
Problema Lowest Common Ancestor Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.24 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

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

const int NMax = 100000, LgMax = 17;

vector <int> g[NMax + 5];
int n, m;
int a[LgMax + 5][NMax + 5], level[NMax + 5];

void Read(){
    fin >> n >> m;
    for (int i = 2; i <= n; i++){
        fin >> a[0][i];
        g[a[0][i]].push_back(i);
    }
}

void Precalculate(){
    for (int i = 1; i <= LgMax; i++)
        for (int j = 1; j <= n; j++)
            a[i][j] = a[i - 1][a[i - 1][j]];
}

void Levels(int node){
    level[node] = level[a[0][node]] + 1;
    for (auto other : g[node])
        Levels(other);
}

int LCA(int x, int y){
    if (level[x] > level[y])
        swap(x, y);
    int dif = level[y] - level[x];
    for (int i = LgMax; i >= 0; i--)
        if ((1 << i) & dif)
            y = a[i][y];
    if (x == y)
        return x;
    for (int i = LgMax; i >= 0; i--)
        if (a[i][x] != a[i][y]){
            x = a[i][x];
            y = a[i][y];
        }
    return a[0][x];
}

int main(){
    Read();
    Precalculate();
    Levels(1);
    while (m--){
        int x, y;
        fin >> x >> y;
        fout << LCA(x, y) << '\n';
    }
    return 0;
}