Cod sursa(job #2486147)

Utilizator Dragos1226Dragos Chileban Dragos1226 Data 2 noiembrie 2019 13:03:03
Problema Lowest Common Ancestor Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.83 kb
#include<bits/stdc++.h>
using namespace std;
ifstream in("lca.in");
ofstream out("lca.out");
/// Aduc x si y la acelasi nivel
/// Urc simultan sa aflu LCA
const int NMax = 100000;
vector <int> G[NMax+5];
int Lvl[NMax+5], N, M, TT[NMax+5];
void Read() {
    in >> N >> M;
    for (int i = 2; i <= N; i++) {
        in >> TT[i];
        G[TT[i]].push_back(i);
    }
}

void DFS(int Nod) {

    for (auto Vecin : G[Nod])
    {
        Lvl[Vecin] = Lvl[Nod] + 1;
        DFS(Vecin);
    }

}

void LCA(int x,int y) {
    if(Lvl[x] < Lvl[y])
        swap(x,y);
    while(Lvl[x]!=Lvl[y]) {
        x=TT[x];
    }
    while(x!=y) {
        x=TT[x];
        y=TT[y];
    }
    out << x << '\n';
}
int main() {
    Read();
    DFS(1);
    int x,y;
    while(M--) {
        in >> x >> y;
        LCA(x,y);
    }
}