Cod sursa(job #2973328)

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

FILE *fin, *fout;

int main()
{
  ios::sync_with_stdio(false);

  fin = fopen("lca.in", "r");
  fout = fopen("lca.out", "w");

  int n, m;
  fscanf(fin, "%d %d", &n, &m);

  vector<int> asc(n + 1), row(n + 1);
  row[1] = 1;
  for (int i = 2; i <= n; i++)
  {
    fscanf(fin, "%d", &asc[i]);
    row[i] = row[asc[i]] + 1;
  }

  for (int i = 1; i <= m; i++)
  {
    int x, y;
    fscanf(fin, "%d %d", &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];

    fprintf(fout, "%d\n", x);
  }

  return 0;
}