Cod sursa(job #2607307)

Utilizator maramihaliMara Mihali maramihali Data 29 aprilie 2020 16:30:07
Problema Lowest Common Ancestor Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.28 kb
#include <bits/stdc++.h>

using namespace std;

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

const int N = 100001;

int lst[N], urm[2 * N], vf[2 * N], nr, ti[N], to[N], t[17][N], timp;

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)
{
    if(ti[x]<=ti[y] && to[y]<=to[x])
        return x;
    int pas = 16;
    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 = 1; i < n; i++)
    {
        int x;
        in >> x;
        adauga(x, i + 1);
        t[0][i + 1] = x;
    }

    dfs(1);
    for(int i = 1; i < 17; i++)
        for(int j = 1; j <= n; j++)
    {
        t[i][j] = t[i - 1][t[i - 1][j]];
    }
    for(int i = 1; i <= m; i++)
    {
        int x ,y;
        in >> x >> y;
        out << lca(x, y) << "\n";
    }
    return 0;
}