Cod sursa(job #2392263)

Utilizator ezioconnorVlad - Gabriel Iftimescu ezioconnor Data 29 martie 2019 20:38:32
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.08 kb
#include <stdio.h>
#include <vector>

const int MAX_N = 100000;
const int SIZE = 320;

int father[1 + MAX_N];
std::vector<int> G[1 + MAX_N];
int pos[1 + MAX_N];
int depth[1 + MAX_N];
int ancestor[1 + MAX_N];

void dfs(int u, int T, int lev) {
  depth[u] = lev;
  ancestor[u] = T;
  if (lev % SIZE == 0)
    T = u;
  for (int v : G[u])
    if (father[u] != v)
      dfs(v, T, lev + 1);
}

int lca(int x, int y) {
  while (ancestor[x] != ancestor[y]) {
    if (depth[x] > depth[y])
      x = ancestor[x];
    else
      y = ancestor[y];
  }
  while (x != y) {
    if (depth[x] > depth[y])
      x = father[x];
    else
      y = father[y];
  }
  return x;
}

int main() {

  freopen("lca.in", "r", stdin);
  freopen("lca.out", "w", stdout);

  int n, q;
  scanf("%d%d", &n, &q);
  for (int i = 2; i <= n; i++) {
    scanf("%d", &father[i]);
    G[father[i]].push_back(i);
    G[i].push_back(father[i]);
  }

  dfs(1, 0, 0);
  for (int i = 1; i <= q; i++) {
    int x, y;
    scanf("%d%d", &x, &y);
    printf("%d\n", lca(x, y));
  }

  return 0;
}