Cod sursa(job #1600858)

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