Cod sursa(job #2475890)

Utilizator greelioGreenio Greely greelio Data 17 octombrie 2019 18:55:21
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1 kb
#include<bits/stdc++.h>
#define N 103000

using namespace std;

int n,m,lvl[N], dp[N][30];
vector<int>V[N];
void DFS(int x, int h) {
    lvl[x]=h;
    for (auto it:V[x]) {
        DFS(it, h+1);
    }
}

int main() {
    ifstream cin("lca.in");
    ofstream cout("lca.out");
    cin>>n>>m;
    for (int i=2; i<=n; i++) {
        int x; cin>>x;
        dp[i][0]=x;
        V[x].push_back(i);
    }

    for (int i=2; i<=n; i++) {
        for (int j=1; (1<<j)<=n; j++) {
            dp[i][j] = dp[dp[i][j-1]][j-1];
        }
    }
    DFS(1,0);

    while (m--) {
        int x,y, p=0; cin>>x>>y;
        while (lvl[x]!=lvl[y]) {
            if (lvl[x]<lvl[y]) swap(x,y);
            p=0;
            while (dp[x][p+1] && lvl[dp[x][p+1]]>=lvl[y]) p++;
            x = dp[x][p];
        }

        while (x!=y) {
            p=0;
            while (dp[x][p+1]!=dp[y][p+1]) p++;
            x=dp[x][p];
            y=dp[y][p];
        }
        cout<<x<<'\n';
    }

    return 0;
}