Cod sursa(job #2986425)

Utilizator tryharderulbrebenel mihnea stefan tryharderul Data 28 februarie 2023 16:57:50
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.18 kb
#include <bits/stdc++.h> 

using namespace std;

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

const int NMAX = 100003;
const int LOGMAX = 20;

int n, q;
int up[NMAX][LOGMAX+2];
int depth[NMAX];
vector<int> g[NMAX];

int lca(int x, int y) {
    if(depth[x] < depth[y]) swap(x, y);
    int diff = depth[x] - depth[y];
    for(int i = LOGMAX; i >= 0; i--)
        if((1<<i) & diff)
            x = up[x][i];
    if(x == y) return x;
    for(int i = LOGMAX; i >= 0; i--) 
        if(up[x][i] != up[y][i]) {
            x = up[x][i];
            y = up[y][i];
        }
    return up[x][0];
}

void dfs(int node, int parent) {
    for(int son : g[node]) {
        if(son == parent) continue ;
        depth[son] = depth[node] + 1;
        dfs(son, node);
    }
}

int main() {

    in >> n >> q;
    for(int i = 2; i <= n; i++) {
        int x; in >> x;
        g[x].push_back(i);
        up[i][0] = x;
    }
    for(int j = 1; j <= LOGMAX; j++)
        for(int i = 1; i <= n; i++)
            up[i][j] = up[up[i][j-1]][j-1];
    dfs(1, 1);

    while(q--) {
        int x, y;
        in >> x >> y;
        out << lca(x, y) << '\n';
    }

    return 0;
}