Cod sursa(job #1881458)

Utilizator paulstepanovStepanov Paul paulstepanov Data 16 februarie 2017 14:48:39
Problema Lowest Common Ancestor Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 0.95 kb
#include <iostream>
#include <fstream>
#include <vector>
#define  Nmax 100005
using namespace std;
ifstream fin("lca.in");
ofstream fout("lca.out");

vector <int> G[Nmax];
int N,M,TT[Nmax],Level[Nmax],Use[Nmax];

void Read()
{
    fin>>N>>M;
    for(int i=2;i<=N;++i)
            {
            fin>>TT[i];
            G[TT[i]].push_back(i);
            }
}

void DFS(int Node)
{
    Use[Node]=1;
    for(int i=0;i<G[Node].size();++i)
    {
        int Vecin=G[Node][i];
            if(!Use[Vecin])
            {
                Level[Vecin]=Level[Node]+1;
                DFS(Vecin);
            }
    }
}

int LCA(int X,int Y)
{
    if(Level[X]<Level[Y]) swap(X,Y);
    while(Level[X]!=Level[Y])
        X=TT[X];
    while(X!=Y)
    {
        X=TT[X]; Y=TT[Y];
    }
    return X;
}

int main()
{
    Read();
    DFS(1);
    while(M--)
    {
        int x,y;
        fin>>x>>y;
        fout<<LCA(x,y)<<"\n";
    }
}