Cod sursa(job #3378543)

Utilizator Emre12Isleam Emre Emre12 Data 26 noiembrie 2026 19:35:46
Problema Lowest Common Ancestor Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.73 kb
#include <algorithm>
#include <cstdio>

#define MAXN 100000
#define MAXM 2000000

int anc[MAXN][20];
int depth[MAXN];
int cncd, n, m;

static inline void cmpDepth(int node) {
  if (!depth[node] && node != 0) {
    cncd--;
    cmpDepth(anc[node][0]);
    depth[node] = depth[anc[node][0]] + 1;
  }
}
static inline void
cmpAnc(int depth) { // calculeaza ancestorii de adancime depth^2
  for (int i = 1; i < n; i++)
    anc[i][depth] = anc[anc[i][depth - 1]][depth - 1];
}

int climb(int node, int pd) {
  int nn, lvl;
  while (depth[node] != pd) {
    lvl = 20;
    do {
      nn = anc[node][lvl--];
    } while (lvl >= 0 && depth[nn] < pd);
    node = nn;
  }
  return node;
}
int cautBin(int na, int nb, int ld, int hd) {
  int mij = (ld + hd) / 2;
  if (hd - ld <= 1) {
    if (climb(na, hd) == climb(nb, hd))
      return climb(na, hd);
    return climb(na, ld);
  }
  if (climb(na, mij) == climb(nb, mij)) {
    return cautBin(na, nb, mij, hd);
  }
  return cautBin(na, nb, ld, mij - 1);
}
int lca(int na, int nb) {
  int auxa, auxb;
  if (depth[na] > depth[nb])
    std::swap(na, nb);
  if (depth[na] == depth[nb] && na == climb(nb, depth[na]))
    return na;
  return cautBin(na, nb, 0, depth[na]);
}

int main() {
  FILE *fin, *fout;
  fin = fopen("lca.in", "r");
  fout = fopen("lca.out", "w");
  int i;
  // citire
  fscanf(fin, "%d%d", &n, &m);
  for (i = 0; i < n - 1; i++) {
    fscanf(fin, "%d", &anc[i + 1][0]);
    anc[i + 1][0]--;
  }

  // calc adancime
  cncd = n - 1;
  for (i = n - 1; i > 0 && cncd; i--)
    cmpDepth(i);

  // calc stramosi
  for (int depth = 1; (1 << depth) < n; depth++)
    cmpAnc(depth);

  // lca
  int a, b;
  for (int i = 0; i < m; i++) {
    fscanf(fin, "%d%d", &a, &b);
    fprintf(fout, "%d\n", lca(a - 1, b - 1) + 1);
  }
}