Cod sursa(job #1892413)

Utilizator FlorinHajaFlorin Gabriel Haja FlorinHaja Data 24 februarie 2017 22:36:26
Problema Lowest Common Ancestor Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.02 kb
#include <cstdio>
#include <vector>

using namespace std;

int H = 220;
int n,i,x,y,m;
int nv[100005];
int tt[100005];
int ttm[100005];
vector<int>ls[100005];

void df(int x, int tm, int niv) {
    ttm[x] = tm;
    if (niv%H == 0)
        tm = x;
    nv[x] = niv;
    int i, l = ls[x].size(), y;
    for (i = 0; i<l; i++) {
        y = ls[x][i];
        if (nv[y] == 0)
            df(y,x,niv+1);
    }
}

int query(int x, int y) {
    while (ttm[x]!=ttm[y]) {
        if (nv[x]>nv[y])
            x = ttm[x];
        else y=ttm[y];

    }
    while (x != y) {
        if (nv[x]>nv[y])
            x = tt[x];
        else y=tt[y];
    }
    return x;
}

int main() {
    freopen("lca.in","r",stdin);
    freopen("lca.out","w",stdout);
    scanf("%d %d\n", &n,&m);
    for (i = 2; i <= n; i++) {
        scanf("%d ", &tt[i]);
        ls[tt[i]].push_back(i);
    }
    df(1,1,0);
    while (m--) {
        scanf("%d %d\n",&x,&y);
        printf("%d\n",query(x,y));
    }
    return 0;
}