Cod sursa(job #3240928)

Utilizator adimiclaus15Miclaus Adrian Stefan adimiclaus15 Data 24 august 2024 12:23:58
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.27 kb
#include <bits/stdc++.h>

using namespace std;

ifstream f("lca.in");
ofstream g("lca.out");
const int NMAX = 1e5;
int t[NMAX + 1];
int p[NMAX + 1][19];
vector<int> G[NMAX + 1];
int niv[NMAX + 1];

void dfs(int node, int dad) {
    niv[node] = niv[dad] + 1;
    for(auto next : G[node]) {
        if(!niv[next]) {
            dfs(next, node);
        }
    }
}

int lca(int x, int y) {
    if(niv[x] != niv[y]) {
        if(niv[x] < niv[y]) {
            swap(x, y);
        }
        int dist = niv[x] - niv[y];
        for(int i = 0; (1 << i) <= dist; i++) {
            if((dist & (1 << i))) {
                x = p[x][i];
            }
        }
    }
    if(x == y) {
        return x;
    }
    for(int i = 18; i >= 0; i--) {
        if(p[x][i] != p[y][i]) {
            x = p[x][i];
            y = p[y][i];
        }
    }
    return p[x][0];
}


int main() {
    int n, m;
    f >> n >> m;
    for(int i = 2; i <= n; i++) {
        f >> t[i];
        p[i][0] = t[i];
        G[i].push_back(t[i]);
        G[t[i]].push_back(i);
    }
    dfs(1, 0);
    for(int j = 1; j <= 18; j++) {
        for(int i = 1; i <= n; i++) {
            p[i][j] = p[p[i][j - 1]][j - 1];
        }
    }
    while(m--) {
        int x, y;
        f >> x >> y;
        g << lca(x, y) << '\n';
    }
    return 0;
}