Cod sursa(job #3266433)

Utilizator vvalentinCiun Valentin vvalentin Data 8 ianuarie 2025 17:40:08
Problema Lowest Common Ancestor Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.91 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], ans;
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]) {
        if (T[x] == y) {
            return y;
        }
        x = T[x];
    }
    while (T[x] != T[y]) {
        x = T[x];
        y = T[y];
    }
    return T[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;
        ans = 0;
        if (x < y) swap(x, y);
        fout << lca(x, y) << '\n';
    }


    return 0;
}