Cod sursa(job #2376123)

Utilizator DanielPanteaDaniel Pantea DanielPantea Data 8 martie 2019 13:44:08
Problema Lowest Common Ancestor Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.88 kb
#include <fstream>
#include <vector>
using namespace std;

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

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

}

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;
}

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

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

int main()
{
    Read();
    SolveandPrint();
    return 0;
}