Cod sursa(job #2831945)

Utilizator rares89_Dumitriu Rares rares89_ Data 12 ianuarie 2022 14:59:43
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.31 kb
#include <fstream>
#include <vector>
#include <bitset>

using namespace std;

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

int n, q, x, y, up[100005][17], d[100005], LOG;
vector<int> t[100005];
bitset<100005> v;
// d - depth

void dfs(int nod) {
    for(int i : t[nod]) {
        if(!v[i]) {
            v[i] = true;
            up[i][0] = nod;
            d[i] = d[nod] + 1;
            for(int j = 1; j < LOG; j++) {
                up[i][j] = up[ up[i][j - 1] ][j - 1];
            }
            dfs(i);
        }
    }
}

int lca(int a, int b) {
    if(d[a] < d[b]) {
        swap(a, b);
    }
    int k = d[a] - d[b];
    for(int i = LOG - 1; i >= 0; i--) {
        if(k & (1 << i)) {
            a = up[a][i];
        }
    }
    if(a == b) {
        return a;
    }
    for(int i = LOG - 1; i >= 0; i--) {
        if(up[a][i] != up[b][i]) {
            a = up[a][i];
            b = up[b][i];
        }
    }
    return up[a][0];
}

int main() {
    fin >> n >> q;
    t[0].push_back(0);
    for(int i = 1; i < n; i++) {
        fin >> x;
        t[x - 1].push_back(i);
    }
    while((1 << LOG) <= n) {
        LOG++;
    }
    dfs(0);
    for(int i = 1; i <= q; i++) {
        fin >> x >> y;
        fout << lca(x - 1, y - 1) + 1 << "\n";
    }
    return 0;
}