Cod sursa(job #2649302)

Utilizator retrogradLucian Bicsi retrograd Data 14 septembrie 2020 11:35:41
Problema Lowest Common Ancestor Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.06 kb
#include <bits/stdc++.h>

using namespace std;

struct Stack { 
  Stack *nxt = nullptr, *jump = nullptr;
  int sz; 
};
vector<Stack> T;

void Init(Stack* x) {
  if (x->jump != nullptr) return;
  Stack* nxt = x->nxt;
  if (nxt == nullptr) {
    x->sz = 0; x->jump = x;
  } else {
    Init(nxt);
    x->sz = 1 + nxt->sz;
    Stack* mid = nxt->jump;
    if (x->sz + mid->jump->sz == 2 * mid->sz)
      x->jump = mid->jump;
    else x->jump = nxt;
  }
}

Stack* Query(Stack* a, Stack* b) {
  Init(a); Init(b);
  if (a->sz < b->sz) swap(a, b);
  while (a->sz > b->sz)
    a = (a->jump->sz >= b->sz ? a->jump : a->nxt);
  while (a != b) {
    if (a->jump != b->jump)
      a = a->jump, b = b->jump;
    else a = a->nxt, b = b->nxt;
  }
  return a;
}

int main() {
  ifstream cin("lca.in");
  ofstream cout("lca.out");
  int n, q; cin >> n >> q;
  T.resize(n);
  for (int i = 1; i < n; ++i) { 
    int par; cin >> par; --par;
    T[i].nxt = &(T[par]);
  }
  for (int i = 0; i < q; ++i) {
    int a, b; cin >> a >> b; --a; --b;
    cout << Query(&(T[a]), &(T[b])) - (&(T[0])) + 1 << '\n';
  }
}