Cod sursa(job #3297385)

Utilizator Arhiva_EducationalaArhiva Educationala Arhiva_Educationala Data 22 mai 2025 16:05:40
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.33 kb
#include <bits/stdc++.h>

using namespace std;

const int NMAX = 1e5;

vector <int> children[NMAX + 1];
int father[NMAX + 1];
int depth[NMAX + 1];
int start[NMAX + 1];
int finish[NMAX + 1];
int jump[NMAX + 1];

int timp = 0;
void dfs( int node ) {
    start[node] = ++timp;
    for ( auto vec : children[node] ) {
        depth[vec] = depth[node] + 1;
        father[vec] = node;
        if ( depth[node] - depth[jump[node]] == depth[jump[node]] - depth[jump[jump[node]]] ) {
            jump[vec] = jump[jump[node]];
        } else {
            jump[vec] = node;
        }
        dfs( vec );
    }

    finish[node] = timp;
}

bool isAnc( int a, int b ) {
    return start[a] <= start[b] && finish[b] <= finish[a];
}
int lca( int a, int b ) {
    while ( a != b ) {
        if ( depth[a] < depth[b] ) swap( a, b );
        if ( isAnc( jump[a], b ) ) a = father[a];
        else a = jump[a];
    }
    return a;
}
int main() {
    ifstream fin( "lca.in" );
    ofstream fout( "lca.out" );
    int n, m;
    fin >> n >> m;

    for ( int i = 2, p; i <= n; i ++ ) {
        fin >> p;
        children[p].push_back( i );
    }
    father[1] = jump[1] = depth[1] = 1;

    dfs( 1 );
    for ( int i = 1, a, b; i <= m; i ++ ) {
        fin >> a >> b;
        fout << lca( a, b ) << '\n';
    }
    return 0;
}