Cod sursa(job #3169259)

Utilizator Allie28Radu Alesia Allie28 Data 14 noiembrie 2023 16:08:08
Problema Lowest Common Ancestor Scor 30
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.39 kb
#include <fstream>
#include <iostream>
#include <queue>
#include <vector>

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

const int LMAX = 100005;
int father[LMAX], str[LMAX][20], depth[LMAX];

int main() {
    int n, m, i,j;
    fin >> n >> m;
    for (i = 2; i <= n; i++) {
        fin>>father[i];
        depth[i] = depth[father[i]] + 1;
        str[i][0] = father[i];
    }
    for (j = 1; j < 20; j++) {
        for (i = 1; i <= n; i++) {
            //stramosul i de ord j este stramosul de ord j-1 al stramosului i de ord j-1
            str[i][j] = str[str[i][j-1]][j-1];
        }
    }
    while (m--) {
        int x, y;
        fin >> x >> y;
        if (depth[x] < depth[y]) {
            swap(x, y);
        }
        int p = depth[x] - depth[y];
        for (j = 19; j >= 0 && p; j--) {
            if ((1<<j) <= p) {
                x = str[x][j];
                p = p - (1<<j);
            }
        }
        ///acum x si y sunt la acelasi nivel
        while (x != y) {
            j = 19;
            int shift = (1<<j);
            while (j >= 0 && str[x][shift] == str[y][shift]) {
                j--;
                shift = (shift>>1);
            }
            x = str[x][shift];
            y = str[y][shift];
        }
        fout<<x<<endl;

    }




    fin.close();
    fout.close();

    return 0;
}