Cod sursa(job #1184901)

Utilizator AlexandruValeanuAlexandru Valeanu AlexandruValeanu Data 14 mai 2014 15:43:34
Problema Lowest Common Ancestor Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 0.92 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

const int Nmax = 100000 + 2;

vector <int> G[Nmax];
int depth[Nmax];
int tata[Nmax];
int N, M;

void DFS( int nod, int d )
{
    depth[nod] = d;

    for ( auto x: G[nod] )
    {
        if ( tata[x] == 0 )
        {
            tata[x] = nod;
            DFS( x, d + 1 );
        }
    }
}

int lca( int x, int y )
{
    while ( x != y )
    {
        if ( depth[x] > depth[y] )
                x = tata[x];
        else
                y = tata[y];
    }

    return x;
}

int main()
{
    ifstream f("lca.in");
    ofstream g("lca.out");

    f >> N >> M;

    for ( int i = 2, a; i <= N; ++i )
    {
        f >> a;
        G[a].push_back( i );
    }

    DFS( 1, 0 );

    for ( int i = 1, a, b; i <= M; ++i )
    {
        f >> a >> b;
        g << lca( a, b ) << "\n";
    }

    return 0;
}