Cod sursa(job #3263304)

Utilizator Xutzu358Ignat Alex Xutzu358 Data 14 decembrie 2024 10:24:36
Problema Lowest Common Ancestor Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.32 kb
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
ifstream fin("lca.in");
ofstream fout("lca.out");

pair<int,int> rmq[200005][18]; 
pair<int,int> euler[200005];
int ind[100005];
int n, m, x, y, k, n1, n2;
int p2[200005];
vector<int> v[100005];


void dfs(int nod, int niv) {
    ind[nod] = ++k;
    euler[k] = {niv, nod};
    for (auto nxt:v[nod]) {
        dfs(nxt, niv+1);
        euler[++k] = {niv, nod};
    }
}

void read() {
    fin >> n >> m;
    for (int i=2;i<=n;i++) {
        fin >> x;
        v[x].push_back(i);
    }
    p2[1] = 0;
    for (int i=2;i<=2*n;i++) {
        p2[i] = p2[i-1];
        if ((1<<(p2[i]+1)) <= i) {
            p2[i]++;
        }
    }
}

void create() {
    for (int j=0;(1<<j)<=k;j++) {
        for (int i=1;i<=k-(1<<j)+1;i++) {
            if (j == 0) {
                rmq[i][j] = euler[i];
            }
            else {
                rmq[i][j] = min(rmq[i][j-1], rmq[i+(1<<(j-1))][j-1]);
            }
        }
    }
}

void query() {
    x = ind[n1]; y = ind[n2];
    int l = (y-x+1);
    fout << min(rmq[x][p2[l]], rmq[y-(1<<p2[l])+1][p2[l]]).second << '\n';
}

int main() {
    read();
    dfs(1, 0);
    create();
    for (int t=1;t<=m;t++) {
        fin >> n1 >> n2;
        query();
    }
    return 0;
}