Cod sursa(job #2364946)

Utilizator nurof3nCioc Alex-Andrei nurof3n Data 4 martie 2019 11:31:29
Problema Lowest Common Ancestor Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.98 kb
#include <iostream>
#include <fstream>
#include <cmath>
#include <vector>

using namespace std;

ifstream f ("lca.in");
ofstream g ("lca.out");

const int NMAX = 100001;
const int H = 19;

int N, M;
int T[NMAX], T2[NMAX], niv[NMAX];
vector<int> G[NMAX];

void DFS (int x, int t2, int lev) {
    niv[x] = lev;
    T2[x] = t2;
    if(lev % H == 0)
        t2 = x;

    for (auto y : G[x])
        DFS (y, t2, lev + 1);
}

int lca (int x, int y) {
    while(T2[x] != T2[y])
        if(niv[x] > niv[y])
            x = T2[x];
        else
            y = T2[y];
    while(x != y)
        if(niv[x] > niv[y])
            x = T[x];
        else
            y = T[y];
    return x;
}

int main() {
    f >> N >> M;
    for (int i = 2; i <= N; i++) {
        f >> T[i];
        G[T[i]].push_back(i);
    }

    DFS(1, 0, 0);

    int x, y;
    for (int i = 1; i <= M; i++) {
        f >> x >> y;
        g << lca (x, y) << '\n';
    }

    return 0;
}