Cod sursa(job #3206833)

Utilizator ililogIlinca ililog Data 24 februarie 2024 11:27:17
Problema Lowest Common Ancestor Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.39 kb
using namespace std;
#include<iostream>
#include<fstream>
#include<cmath>
#include<vector>

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

int n, q;
int dp[40][100005], tin[100005], tout[100005];
int timer;
int pmax;
vector<int> G[100005];

int log(int x) {
    int ans = 0;
    while ((1<<ans) < x) {
        ans++;
    }
    return ans;
}

void dfs(int nod, int tata) {
    tin[nod] = ++timer;
    dp[0][nod] = tata;
    
    for (int i = 1; i<=pmax; i++) {
        dp[i][nod] = dp[i-1][dp[i-1][nod]];
    }
    
    for (auto it: G[nod]) {
        if (it != tata) {
            dfs(it, nod);
        }
    }
    
    tout[nod] = ++timer;
}

bool isAncestor(int a, int b) {
    if (tin[a] <= tin[b] && tout[a] >= tout[b]) {
        return 1;
    }
    return 0;
}

int lca(int a, int b) {
    if (isAncestor(a, b)) {
        return a;
    }
    if (isAncestor(b, a)) {
        return b;
    }
    
    for (int i = pmax; i>=0; i--) {
        if (!isAncestor(dp[i][a], b)) {
            a = dp[i][a];
        }
    }
    return dp[0][a];
}

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