Cod sursa(job #1599134)

Utilizator BlueStrutAndrei Prahoveanu BlueStrut Data 13 februarie 2016 17:25:14
Problema Lowest Common Ancestor Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.14 kb
#include<cstdio>
#include<vector>
#include<algorithm>
#include<cmath>
#define max_n 10005
using namespace std;
vector<int> grf[max_n];
int a[20][max_n], i, j, x, y, adancime[max_n], lg, unde_apare[max_n], n, k, nr;
void dfs(int poz, int h){
    vector<int>::iterator it;
    adancime[poz]=h;
    a[0][++lg]=poz;
    if (unde_apare[poz]==0) unde_apare[poz]=lg;
    for (it=grf[poz].begin();it!=grf[poz].end();it++) {
        dfs(*it, h+1);
        a[0][++lg]=poz;
    }
}
inline void rmq(){
    for (i=1;(1<<i)<=lg;i++)
        for (j=1;j<=lg-(1<<i)+1;j++) {
            if (adancime[a[i-1][j]]<=adancime[a[i-1][j+(1<<(i-1))]]) a[i][j]=a[i-1][j];
                else a[i][j]=a[i-1][j+(1<<(i-1))];
        }
}
int main(){
    freopen("lca.in","r",stdin);
    freopen("lca.out","w",stdout);
    scanf("%d%d", &n, &k);
    for (i=2;i<=n;i++) {scanf("%d", &x); grf[x].push_back(i);}
    dfs(1,0);
    rmq();
    for (i=1;i<=k;i++) {
        scanf("%d%d", &x, &y);
        x=unde_apare[x]; y=unde_apare[y]; if (x>y) swap(x,y);
        nr=log2(y-x+1);
        printf("%d\n", min(a[nr][x], a[nr][y-(1<<nr)+1]));
    }
    return 0;
}