Cod sursa(job #3230122)

Utilizator Tudor06MusatTudor Tudor06 Data 19 mai 2024 12:15:37
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.23 kb
#include <bits/stdc++.h>

using namespace std;

const int NMAX = 1e5;

int depth[NMAX + 1];
int father[NMAX + 1];
int jump[NMAX + 1];

void dfs( int node ) {
    int p = father[node];
    if ( !jump[p] ) dfs( p );
    depth[node] = depth[p] + 1;
    if ( depth[p] - depth[jump[p]] == depth[jump[p]] - depth[jump[jump[p]]] ) jump[node] = jump[jump[p]];
    else jump[node] = p;
}

int kthAnc( int a, int targetD ) {
    while ( depth[a] > targetD ) {
        if ( depth[jump[a]] >= targetD ) a = jump[a];
        else a = father[a];
    }
    return a;
}
int lca( int a, int b ) {
    if ( depth[a] < depth[b] ) swap( a, b );
    a = kthAnc( a, depth[b] );
    while ( a != b ) {
        if ( jump[a] != jump[b] ) {
            a = jump[a];
            b = jump[b];
        } else {
            a = father[a];
            b = father[b];
        }
    }
    return a;
}
int main() {
    ifstream fin( "lca.in" );
    ofstream fout( "lca.out" );
    int n, q;
    fin >> n >> q;
    for ( int i = 2; i <= n; i ++ ) {
        fin >> father[i];
    }
    father[1] = jump[1] = 1;
    for ( int i = 2; i <= n; i ++ ) if ( !jump[i] ) dfs( i );
    for ( int i = 1, a, b; i <= q; i ++ ) {
        fin >> a >> b;
        fout << lca( a, b ) << '\n';
    }
    return 0;
}