Cod sursa(job #2972503)

Utilizator octavi26octavian octavi26 Data 29 ianuarie 2023 16:38:23
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.22 kb
#include <bits/stdc++.h>
#define N 100008

using namespace std;

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

int n, q;
int Dad[N];
int first;
vector<int> g[N];

void Citire()
{
    int i;
    fin >> n >> q;
    for( i=2; i<=n; i++ )
    {
        fin >> Dad[i];
        g[ Dad[i] ].push_back(i);
    }
}

int Up[N][26];
int depth[N];

void DFS( int x )
{
    for( auto y : g[x] )
    {
        Up[y][0] = x;
        depth[y] = depth[x] + 1;
        for( int j=1; (1<<j) <= n; j++ )
            Up[y][j] = Up[ Up[y][j - 1] ][j - 1];
        DFS(y);
    }
}

int lca( int x, int y )
{
    if( depth[x] < depth[y] )
        swap(x, y);

    int k = depth[x] - depth[y];
    for( int j = 20; j >= 0; j-- )
        if( k & (1 << j) )
            x = Up[x][j];

    if( x == y )
        return x;

    for( int j = 20; j >= 0; j-- )
        if( Up[x][j] != Up[y][j] )
        {
            x = Up[x][j];
            y = Up[y][j];
        }
    return Up[x][0];
}

void Rezolvare()
{
    int i;
    DFS(1);
    int x, y;
    while( q-- )
    {
        fin >> x >> y;
        fout << lca(x, y) << "\n";
    }
}

int main()
{
    Citire();
    Rezolvare();
    return 0;
}