Cod sursa(job #2972890)

Utilizator andreibazavanAndrei Bazavan andreibazavan Data 30 ianuarie 2023 16:30:17
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.53 kb
#include <bits/stdc++.h>

using namespace std;
ifstream fin("lca.in");
ofstream fout("lca.out");
vector <int> G[100005];
int n, m, contor, timer[100005], depth[300005], path[300005], lg[300005], RMQ[18][300005];
void DFS(int nod, int lvl)
{
    contor++;
    timer[nod]=contor;
    path[contor]=nod;
    depth[contor]=lvl;
    for(int i=0;i<G[nod].size();++i)
    {
        DFS(G[nod][i], lvl+1);
        path[++contor]=nod;
        depth[contor]=lvl;
    }
}
void Build_RMQ()
{
    for(int i=2;i<=contor;i++)
        lg[i]=lg[(i>>1)]+1;
    for(int i=1;i<=contor;i++)
        RMQ[0][i]=i;
    for(int i=1;(1<<i)<=contor; i++)
        for(int j = 1; j <= contor- (1 << i); j++)
        {
            int lg2 = 1 << (i - 1);
            if(depth[RMQ[i - 1][j]] < depth[RMQ[i - 1][j + lg2]])
                RMQ[i][j] = RMQ[i - 1][j];
            else
                RMQ[i][j] = RMQ[i - 1][j + lg2];
        }
}

int LCA(int x, int y)
{
    x = timer[x], y = timer[y];
    if(x > y) swap(x, y);
    int lg2 = lg[y - x + 1], poz;
    if(depth[RMQ[lg2][x]] < depth[RMQ[lg2][y - (1 << lg2) + 1]])
        poz = RMQ[lg2][x];
    else
        poz = RMQ[lg2][y - (1 << lg2) + 1];
    return path[poz];
}
int main()
{
    fin>>n>>m;
    for(int i=2;i<=n;++i)
    {
        int x;
        fin>>x;
        G[x].push_back(i);
    }
    DFS(1, 1);
    Build_RMQ();
    while(m--)
    {
        int x, y;
        fin>>x>>y;
        fout<<LCA(x, y)<<'\n';
    }
   //cout << "Hello world!" << endl;
    return 0;
}