Cod sursa(job #3277920)

Utilizator Allie28Radu Alesia Allie28 Data 18 februarie 2025 00:20:50
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.25 kb
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
#include <set>
#include <algorithm>

using namespace std;

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

const int LMAX = 100005;
const int MOD = 1000000007;

int depth[LMAX], str[21][LMAX], father[LMAX];

int lowestca(int x, int y) {
    if (depth[x] < depth[y]) swap(x, y);
    int p = depth[x] - depth[y];
    for (int i = 20; i >= 0 && p; i--) {
        if ((1<<i) <= p) {
            x = str[i][x];
            p = p - (1<<i);
        }
    }
    while (x != y) {

        p = 20;
        while (p > 0 && str[p][y] == str[p][x]) {
            p--;
        }
        x = str[p][x];
        y = str[p][y];
    }
    return x;
}

int main() {
    int n, i, j, m;
    fin>>n>>m;
    for (i = 2; i <= n; i++) {
        fin>>father[i];
        depth[i] = depth[father[i]] + 1;
        str[0][i] = father[i];
    }
    for (j = 1; j <= 20; j++) {
        for (i = 1; i <= n; i++) {
            str[j][i] = str[j - 1][str[j - 1][i]];
        }
    }
    int lca;
    while (m--) {
        int x, y;
        fin>>x>>y;
        lca = lowestca(x, y);
        fout<<lca<<endl;

    }



    fin.close();
    fout.close();
    return 0;
}