Cod sursa(job #1989598)

Utilizator Mihai_PredaPreda Mihai Dragos Mihai_Preda Data 8 iunie 2017 08:39:17
Problema Lowest Common Ancestor Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.32 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

const int nMax = 100005;
const int logMax = 20;

int n, m;

int father[logMax][nMax]; //al 2^i-ulea father al lui j
vector<int> child[nMax];
int nivel[nMax];

int Query(int x, int y)
{
    if(nivel[x] < nivel[y])
        swap(x, y);
    int step;
    for(step = 0; (1 << step) < n; ++step);
    for(int i = step; i >= 0; --i)
        if(nivel[father[i][x]] >= nivel[y])
            x = father[i][x];
    if(x == y)
        return x;
    for(int i = step; i >= 0; --i)
        if(father[i][x] != father[i][y])
            x = father[i][x], y = father[i][y];
    return father[0][x];
}

void DFS(int current, int niv)
{
    nivel[current] = niv;
    for(auto c:child[current])
        DFS(c, niv + 1);
}

int main()
{
    ifstream in("lca.in");
    ofstream out("lca.out");
    in >> n >> m;
    father[0][1] = -1;
    for(int i = 2; i <= n; ++i)
    {
        in >> father[0][i];
        child[father[0][i]].push_back(i);
    }
    DFS(1, 1);
    for(int i = 1; (1 << i) <= n; ++i)
        for(int j = 1; j <= n; ++j)
            father[i][j] = father[i-1][father[i-1][j]];
    int x, y;
    for(int i = 1; i <= m; ++i)
    {
        in >> x >> y;
        out << Query(x, y) << "\n";
    }
    return 0;
}