Cod sursa(job #2649301)

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

using namespace std;

struct Node { int parent = -1, jump = -1, depth; };
vector<Node> T;

void Init(int node) {
  if (T[node].jump != -1) return;
  int par = T[node].parent;
  if (par == -1) {
    T[node].depth = 0;
    T[node].jump = node; 
  } else {
    Init(par);
    T[node].depth = 1 + T[par].depth;
    int mid = T[par].jump;
    if (T[node].depth + T[T[mid].jump].depth == 2 * T[mid].depth)
      T[node].jump = T[mid].jump;
    else T[node].jump = par;
  }
}

int Query(int a, int b) {
  Init(a); Init(b);
  if (T[a].depth < T[b].depth) swap(a, b);
  while (T[a].depth > T[b].depth)
    a = (T[T[a].jump].depth >= T[b].depth ? T[a].jump : T[a].parent);
  while (a != b) {
    if (T[a].jump != T[b].jump)
      a = T[a].jump, b = T[b].jump;
    else a = T[a].parent, b = T[b].parent;
  }
  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].parent = par;
  }
  for (int i = 0; i < q; ++i) {
    int a, b; cin >> a >> b; --a; --b;
    cout << Query(a, b) + 1 << '\n';
  }
}