Cod sursa(job #2649298)

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

using namespace std;

vector<int> parent, jump, depth;

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

int Query(int a, int b) {
  Init(a); Init(b);
  if (depth[a] < depth[b]) swap(a, b);
  while (depth[a] > depth[b])
    a = (depth[jump[a]] >= depth[b] ? jump[a] : parent[a]);
  assert(depth[a] == depth[b]);
  while (a != b) {
    if (jump[a] != jump[b])
      a = jump[a], b = jump[b];
    else a = parent[a], b = parent[b];
  }
  return a;
}

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