Cod sursa(job #2973325)

Utilizator LukyenDracea Lucian Lukyen Data 31 ianuarie 2023 18:59:27
Problema Lowest Common Ancestor Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.62 kb
#include <vector>
#include <fstream>
using namespace std;

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

int main()
{
  ios::sync_with_stdio(false);
  fin.tie(NULL);
  fout.tie(NULL);

  int n, m;
  fin >> n >> m;

  vector<int> asc(n + 1), row(n + 1);
  row[1] = 1;
  for (int i = 2; i <= n; i++)
    fin >> asc[i], row[i] = row[asc[i]] + 1;

  for (int i = 1; i <= m; i++)
  {
    int x, y;
    fin >> x >> y;

    if (row[x] < row[y])
      swap(x, y);

    while (row[x] > row[y])
      x = asc[x];

    while (x != y)
      x = asc[x], y = asc[y];

    fout << x << "\n";
  }

  return 0;
}