Cod sursa(job #1958954)

Utilizator dumbraveanbDumbravean Bogdan dumbraveanb Data 8 aprilie 2017 21:59:16
Problema Lowest Common Ancestor Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.12 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

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

#define Nmax 100005

int n, m, T[Nmax], x, y, Lca[Nmax][20], L[Nmax];

int Query(int x, int y) {
    if(L[x] < L[y]) {
        int aux = x;
        x = y;
        y = aux;
    }

    int log = 1;
    while(1 << (log + 1) <= L[x]) ++log;

    for(int i = log; i >= 0; --i)
        if(L[x] - (1 << i) >= L[y])
            x = Lca[x][i];

    if(x == y)
        return x;

    for(int i = log; i >= 0; --i)
        if(Lca[x][i] && Lca[x][i] != Lca[y][i])
            x = Lca[x][i], y = Lca[y][i];

    return T[x];
}

int main()
{
    fin >> n >> m;
    for(int i = 2; i <= n; ++i) {
        fin >> T[i];
        L[i] = L[T[i]] + 1;
        Lca[i][0] = T[i];
    }
    Lca[1][0] = T[1];

    for(int j = 1; 1 << j < n; ++j)
        for(int i = 1; i <= n; ++i)
            if(Lca[i][j - 1])
                Lca[i][j] = Lca[Lca[i][j - 1]][j - 1];

    for(int i = 1; i <= m; ++i) {
        fin >> x >> y;
        fout << Query(x, y) << '\n';
    }
    return 0;
}