Cod sursa(job #2883028)

Utilizator cdenisCovei Denis cdenis Data 1 aprilie 2022 01:36:39
Problema Lowest Common Ancestor Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.11 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

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

const int MAX=1e5+5;
const int LOG=18;
int n,m,up[LOG][MAX],depth[MAX];
vector < int > children[MAX];

void DFS(int nod)
{
    depth[nod]=depth[up[0][nod]]+1;
    for(int child : children[nod])
    {
        for(int i=1;(1<<i)<=n;i++)
            up[i][child]=up[i-1][up[i-1][child]];
        DFS(child);
    }
}

int LCA(int a, int b)
{
    if(depth[a]<depth[b])
        swap(a,b);
    int k=depth[a]-depth[b];
    for(int i=LOG-1;i>=0;i--)
        if(k&(1<<i))
            a=up[i][a];
    if(a==b)
        return a;
    for(int i=LOG-1;i>=0;i--)
        if(up[i][a]!=up[i][b])
        {
            a=up[i][a];
            b=up[i][b];
        }
    return up[0][a];
}

int main()
{
    fin >> n >> m;
    for(int nod=2;nod<=n;nod++)
    {
        fin >> up[0][nod];
        children[up[0][nod]].push_back(nod);
    }
    DFS(1);
    while(m--)
    {
        int a,b;
        fin >> a >> b;
        fout << LCA(a,b) << '\n';
    }
    return 0;
}