Cod sursa(job #1508956)

Utilizator timicsIoana Tamas timics Data 23 octombrie 2015 11:51:22
Problema Lowest Common Ancestor Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.36 kb
#include<stdio.h>
#include<vector>
#include<algorithm>
using namespace std; 
int K, N, M, x, y, L[200010], e[200010], Lg[200010], poz[100010], rmq[20][400010];
vector<int> g[100010];
 
void dfs(int x, int lev) {
    e[++K] = x;
    L[K] = lev;
    poz[x] = K;
    for(auto y: g[x]) {
        dfs(y,lev+1);
        e[++K] = x;
        L[K] = lev;
    }
}
 
void preprocess_lca() {
    dfs(1,0);
    for(int i=2;i<=K;++i) {
        Lg[i] = Lg[i/2]+1;
    }
    for(int i=1;i<=K;++i) {
        rmq[0][i]=i;
    } 
    for(int i=1;(1<<i) < K; ++i) {
        for(int j=1;j<=K-(1<<i);++j) {
            rmq[i][j] = rmq[i-1][j];
            if(L[rmq[i-1][j + (1<<(i-1))]] < L[rmq[i][j]]) {
                rmq[i][j] = rmq[i-1][j + (1<<(i-1))];
            }
        }
    }
}
 
int lca(int x, int y) {
    int a = poz[x], b = poz[y];
    if(a>b) {
        swap(a,b); 
    }
    int l = Lg[b-a+1];
    int sol = rmq[l][a];
    if(L[sol] > L[rmq[l][b - (1<<l) + 1]]) {
        sol = rmq[l][b - (1<<l) + 1];
    }
    return e[sol];
}
 
int main()
{
    //freopen("input.in","r",stdin);
    freopen("lca.in","r",stdin);
    freopen("lca.out","w",stdout);
    scanf("%d%d",&N,&M);
    for(int i=2;i<=N;++i) {
        scanf("%d",&x);
        g[x].push_back(i);
    } 
    preprocess_lca();
 
    for(int i=1;i<=M;++i) {
        scanf("%d%d",&x,&y);
        printf("%d\n",lca(x,y));
    }
    return 0;
}