Cod sursa(job #2629134)

Utilizator RobertLearnsCDragomir Robert. RobertLearnsC Data 19 iunie 2020 10:48:37
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.31 kb
#include <bits/stdc++.h>
using namespace std;
#define NMAX 100005

int n, m, father[NMAX], depth[NMAX], anc[NMAX], maxD;
vector <int> tree[NMAX];

void getAncestors(int node, int ancestor, int d) {
    anc[node] = ancestor;
    if(depth[node] % d == 0) {
        ancestor = node;
    }
    for(auto son : tree[node]) {
        getAncestors(son, ancestor,  d);
    }
}

int find_lca(int x, int y) {
    while(anc[x] != anc[y]) {
        if(depth[x] > depth[y]) {
            x = anc[x];
        } else {
            y = anc[y];
        }
    }
    while(x != y) {
        if(depth[x] > depth[y]) {
            x = father[x];
        } else {
            y = father[y];
        }
    }
    return x;
}

int rad(int x) {
    if(sqrt(x) == (int)sqrt(x)) return sqrt(x) - 1;
    return (int)sqrt(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]);
        tree[father[i]].push_back(i);
        depth[i] = depth[father[i]] + 1;
        maxD = max(depth[i], maxD);
    }

    getAncestors(1, 1, rad(maxD));

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