Cod sursa(job #2376581)

Utilizator liviu2000Dragomirescu Liviu liviu2000 Data 8 martie 2019 16:29:38
Problema Lowest Common Ancestor Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.87 kb
#include <bits/stdc++.h>
#define N 100005

using namespace std;

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

int n , m ;
int tt[N] , lvl[N] ;
vector<int> graf[N] ;

void citire()
{
    int i ;
    fin >> n >> m ;
    for ( i = 1 ; i < n ; i++ )
    {
        fin >> tt[i+1] ;
        graf[tt[i+1]].push_back(i+1) ;
    }
}

void dfs(int nod)
{
    for ( auto vec : graf[nod] )
    {
        lvl[vec] = lvl[nod]+1 ;
        dfs(vec) ;
    }
}

int lca(int x,int y)
{
    if ( lvl[x] < lvl[y] )
        swap(x,y) ;
    while ( lvl[x] != lvl[y] )
        x = tt[x] ;
    while ( x != y )
    {
        x = tt[x] ;
        y = tt[y] ;
    }
    return x;
}

int main()
{
    int i , x , y ;
    citire() ;
    dfs(1) ;
    for ( i = 1 ; i <= m ; i++ )
    {
        fin >> x >> y ;
        fout << lca(x,y) << '\n' ;
    }
}