Cod sursa(job #2607383)

Utilizator Ioan_AnghelIoan Anghel Ioan_Anghel Data 29 aprilie 2020 17:47:33
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.35 kb
#include <iostream>
#include <fstream>

using namespace std;

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

const int N = 100005, M = 200005, L = 17;
int vf[M], lst[N], urm[M];
int ti[N], to[N], t[L][N];
int timp, nr;

void adauga_lista(int a, int b)
{
    vf[++nr] = b;
    urm[nr] = lst[a];
    lst[a] = nr;
}

void dfs(int x)
{
    ti[x] = ++timp;
    for(int p = lst[x]; p != 0; p = urm[p]){
        int y = vf[p];
        if(ti[y] == 0){
            dfs(y);
            t[0][y] = x;
        }
    }
    to[x] = ++timp;
}

int lca(int x, int y)
{
    if(ti[x] <= ti[y] && to[y] <= to[x]){
        return x;
    }
    int pas = L - 1;
    while(pas >= 0){
        int s = t[pas][x];
        if(s != 0 && (ti[s] > ti[y] || to[y] >to[s])){
            x = s;
        }
        pas--;
    }
    return t[0][x];
}

int main()
{
    int n, m;
    in >> n >> m;
    for(int i = 2; i <= n; i++){
        int a;
        in >> a;
        adauga_lista(a, i);
    }
    dfs(1);
    for(int i = 1; i < L; i++){
        for(int j = 1; j <= n; j++){
            t[i][j] = t[i - 1][t[i - 1][j]];
           // cout << t[i][j] << " ";
        }
       // cout << "\n";
    }
    for(int i = 0; i < m; i++){
        int a, b; in >> a >> b;
        int c = lca(a, b);
        out << c << "\n";
    }

    return 0;
}