Cod sursa(job #2629033)

Utilizator RobertLearnsCDragomir Robert. RobertLearnsC Data 18 iunie 2020 17:30:02
Problema Lowest Common Ancestor Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.68 kb
#include <bits/stdc++.h>
using namespace std;
#define NMAX 100005

int n, m, father[NMAX], depth[NMAX];

int find_lca(int x, int 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);

    scanf("%d%d", &n, &m);

    for(int i = 2; i <= n; i++) {
        scanf("%d", &father[i]);
        depth[i] = depth[father[i]] + 1;
    }

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