Cod sursa(job #3266442)

Utilizator vvalentinCiun Valentin vvalentin Data 8 ianuarie 2025 17:54:19
Problema Lowest Common Ancestor Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.83 kb
#include <bits/stdc++.h>
using namespace std;
ifstream fin ("lca.in");
ofstream fout ("lca.out");
const int NMAX = 1e5;
int N, M, T[NMAX + 2], x, y, nivel[NMAX + 2];
vector<int> arbore[NMAX + 2];

void defese(int x, int niv) {
    nivel[x] = niv;
    for (int i : arbore[x]) {
        defese(i, niv + 1);
    }
}

int lca(int x, int y) {
    while (nivel[x] > nivel[y]) {
        x = T[x];
    }
    while (x != y) {
        x = T[x];
        y = T[y];
    }
    return x;
}

int main() {
    fin >> N >> M;
    for (int i = 2; i <= N; i++) {
        fin >> T[i];
        arbore[T[i]].push_back(i);
    }
    if (nivel[x] < nivel[y]) swap(x, y);
    defese(1, 1);
    while (M--) {
        fin >> x >> y;
        if (nivel[x] < nivel[y]) swap(x, y);
        fout << lca(x, y) << '\n';
    }


    return 0;
}