Cod sursa(job #3358003)

Utilizator TestLicenta123Test Test TestLicenta123 Data 13 iunie 2026 22:50:33
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.38 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <algorithm>

using namespace std;

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

const int N = 1e5 + 5;
const int M = 20;

int n, m;
vector<int> g[N];
int anc[M][N];
int h[N];
int ord[N], nr;

void bfs() {
    queue<int> q;
    q.push(1);
    h[1] = 1;
    while (!q.empty()) {
        int x = q.front();
        q.pop();
        ord[++nr] = x;
        for (int i = 0; i < g[x].size(); i++) {
            int y = g[x][i];
            if (h[y] == 0) {
                h[y] = h[x] + 1;
                anc[0][y] = x;
                q.push(y);
            }
        }
    }
}

int lca(int x, int y) {
    if (h[x] < h[y]) swap(x, y);
    for (int i = M - 1; i >= 0; i--) {
        if (h[anc[i][x]] >= h[y]) x = anc[i][x];
    }
    if (x == y) return x;
    for (int i = M - 1; i >= 0; i--) {
        if (anc[i][x] != anc[i][y]) {
            x = anc[i][x];
            y = anc[i][y];
        }
    }
    return anc[0][x];
}

int main() {
    fin >> n >> m;
    for (int i = 2; i <= n; i++) {
        int x;
        fin >> x;
        g[x].push_back(i);
    }
    bfs();
    for (int j = 1; j < M; j++) {
        for (int i = 1; i <= n; i++) {
            anc[j][i] = anc[j - 1][anc[j - 1][i]];
        }
    }
    while (m--) {
        int x, y;
        fin >> x >> y;
        fout << lca(x, y) << '\n';
    }
    return 0;
}