Cod sursa(job #2486139)

Utilizator IoanaDraganescuIoana Draganescu IoanaDraganescu Data 2 noiembrie 2019 12:54:22
Problema Lowest Common Ancestor Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.9 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

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

const int nmax = 100000;

vector <int> g[nmax + 5];
int tt[nmax + 5], n, m, lev[nmax + 5];

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

void CalcLevel(int nod){
    lev[nod] = lev[tt[nod]] + 1;
    for (auto i : g[nod])
        if (!lev[i])
            CalcLevel(i);
}

int LCA(int x, int y){
    if (lev[x] > lev[y])
        swap(x, y);
    while (lev[y] != lev[x])
        y = tt[y];
    while (x != y){
        x = tt[x];
        y = tt[y];
    }
    return x;
}

void Print(){
    while(m--){
        int x, y;
        fin >> x >> y;
        fout << LCA(x, y) << '\n';
    }
}

int main(){
    Read();
    CalcLevel(1);
    Print();
    return 0;
}