Cod sursa(job #2607305)

Utilizator AlexBosneag26Bosneag Alexandru AlexBosneag26 Data 29 aprilie 2020 16:28:46
Problema Lowest Common Ancestor Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.24 kb
#include <fstream>

using namespace std;

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

const int L = 17, N = 100001, M = 2 * 100001;

int n, m, t[L][N], vf[M], urm[M], lst[M], nr, timp, ti[N], to[N];

void adauga(int x, int y)
{
    vf[++nr] = y;
    urm[nr] = lst[x];
    lst[x] = 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)
{
    int pas = L-1;
    if(ti[x] <= ti[y] && to[y] <= to[x])
        return x;
    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()
{
    in >> n >> m;
    for(int i = 2, x; i <= n; i++)
    {
        in >> x;
        adauga(x, i);
       //adauga(i, x);
    }
    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]];
        }
    }

    for(int i = 1, x, y; i <= m; i++)
    {
        in >> x >> y;
        out << lca(x, y) << "\n";
    }
    return 0;
}