Cod sursa(job #2608095)

Utilizator cezarus30cezarus30 cezarus30 Data 30 aprilie 2020 16:27:21
Problema Lowest Common Ancestor Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.27 kb
#include <iostream>
#include <fstream>

using namespace std;

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

const int N = 100001;
const int M = 100001;
const int L = 18;

int n , m , nr , timel ,  vf [N], urm[N], t[L][N], tb[N] , lst[N], to[N];

void add(int x, int y)
{
    vf[++nr]= y;
    urm[nr]=lst[x];
    lst[x]=nr;
}

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

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

int main()
{
    in>> n >> m;
    for(int i=2; i <= n; i++)
    {
        int a;
        in>>a;
        add(a, i);
    }
    dfs(1);
    for(int i=1; (1 << i )<= n ; 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;
}