Cod sursa(job #2356217)

Utilizator andrei42Oandrei42O andrei42O Data 26 februarie 2019 16:09:12
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.09 kb
#include <bits/stdc++.h>
using namespace std;
ifstream f("lca.in");
ofstream g("lca.out");
const int N = 1 << 17;
vector <int> v[N];
int n, m, e[18][N * 2], i, j, st, dr, k, mi, p, P, start[N], niv[N];
void DFS(int, int);
int main()
{
    f >> n >> m;
    for(int i = 2; i <= n; i++)
    {
        f >> j;
        v[j].push_back(i);
    }
    DFS(1, 1);
    for(int i=1,p=1,P=2; P <= k; i++,p*=2,P*=2)
        for(st=1,mi=p+1,dr=P;dr<=k;st++,mi++,dr++)
            e[i][st]=niv[e[i-1][st]]<niv[e[i-1][mi]]?e[i-1][st]:e[i-1][mi];
    for(; m; m--)
    {
        int x, y;
        f >> x >> y;
        x = start[x]; y = start[y];
        if(x > y)
            swap(x, y);
        i = 31 - __builtin_clz(y - x + 1);
        p = 1 << i;
        y = y - p + 1;
        x = e[i][x];
        y = e[i][y];
        x = niv[x] < niv[y] ? x : y;
        g << x  << '\n';
    }

    return 0;
}
void DFS(int nod, int nivel)
{
    e[0][++k] = nod;
    start[nod] = k;
    niv[nod] = nivel;
    for(auto vec: v[nod])
    {
        DFS(vec, nivel + 1);
        e[0][++k] = nod;
    }
}