Cod sursa(job #2738585)

Utilizator sichetpaulSichet Paul sichetpaul Data 6 aprilie 2021 08:51:14
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.03 kb
#include <bits/stdc++.h>
#define Nmax 100005
#define LG 20
using namespace std;

ifstream fin("lca.in");
ofstream fout("lca.out");

int N, K, Q, L;
int le[Nmax], ri[Nmax], anc[Nmax][LG];
vector<int> G[Nmax];

void DFS(int node, int father) {
    le[node] = ++K;
    anc[node][0] = father;
    for (int i = 1; i <= L; ++i)
        anc[node][i] = anc[anc[node][i - 1]][i - 1];

    for (auto it: G[node])
         DFS(it, node);
    ri[node] = ++K;
}
bool isAnc(int x, int y) {
   return (le[x] <= le[y] && ri[y] <= ri[x]);
}
int lca(int x, int y) {
   if (isAnc(x, y)) return x;
   if (isAnc(y, x)) return y;
   for (int i = L; i >= 0; --i)
      if (!isAnc(anc[x][i], y)) x = anc[x][i];
   return anc[x][0];
}
int main()
{
    fin >> N >> Q;
    L = ceil(log2(N));
    for (int i = 2; i <= N; ++i) {
        int x, y;
        fin >> x;
        G[x].push_back(i);
    }
    DFS(1, 1);

    while (Q--) {
        int x, y;
        fin >> x >> y;
        fout << lca(x, y) << '\n';
    }

    return 0;
}