Cod sursa(job #3338548)

Utilizator uncrownedHojda Adelin uncrowned Data 3 februarie 2026 20:54:44
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.24 kb
#include <bits/stdc++.h>
using namespace std;

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

#define cin fin
#define cout fout

vector<int> g[100001];
const int LOG=18;
int parent[100001][LOG];
int depth[100001];
int n, m;

void dfs(int node, int tata) {
    parent[node][0]=tata;
    for(int i = 1; i < LOG; i++) {
        parent[node][i] = parent[parent[node][i-1]][i-1];
    }
    for(auto i : g[node]) {
        if (i==tata) continue;
        depth[i]=depth[node]+1;
        dfs(i, node);
    }
}

int query(int x, int y) {
    if (depth[x]<depth[y]) swap(x, y);
    int diff = depth[x]-depth[y];
    for(int i = 0; i < LOG; i++) {
        if (diff&(1<<i)) {
            x=parent[x][i];
        }
    }
    if (x==y) return x;
    for(int i = LOG-1; i >= 0; i--) {
        if (parent[x][i]!=parent[y][i]) {
            x = parent[x][i];
            y = parent[y][i];
        }
    }
    return parent[x][0];
}

int main() {

    cin >> n >> m;
    for(int i = 2 ; i<= n; i++) {
        int x;
        cin >> x;
        g[i].push_back(x);
        g[x].push_back(i);
    }
    dfs(1, 0);
    while(m--) {
        int x, y;
        cin >>x >> y;
        cout << query(x,y)<<"\n";
    }
    return 0;
}