Cod sursa(job #2211336)

Utilizator Horia14Horia Banciu Horia14 Data 9 iunie 2018 22:17:33
Problema Lowest Common Ancestor Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.71 kb
#include<cstdio>
#include<vector>
#define MAX_N 100000
#define MAX_LOG 18
using namespace std;

vector<int>g[MAX_N+1];
int sparse[2*MAX_N][MAX_LOG], euler[2*MAX_N], level[2*MAX_N], firstOccurence[MAX_N+1], n, m, k;

inline int log2(int x) {
    return 31 - __builtin_clz(x);
}

void DFS(int node, int l) {
    euler[k] = node;
    level[k] = l;
    firstOccurence[node] = k;
    k++;
    for(auto i : g[node]) {
        DFS(i,1+l);
        euler[k] = node;
        level[k] = l;
        k++;
    }
}

void preprocess(int n) {
    int i, j;
    for(i = 0; i < n; i++)
        sparse[i][0] = i;
    for(j = 1; (1 << j) <= n; j++)
        for(i = 0; i + (1 << j) - 1 < n; i++)
            if(level[sparse[i][j-1]] < level[sparse[i + (1 << (j-1))][j-1]])
                sparse[i][j] = sparse[i][j-1];
            else sparse[i][j] = sparse[i + (1 << (j-1))][j-1];
}

inline int RMQ(int low, int high) {
    int l = high - low + 1;
    int k = log2(l);
    if(level[sparse[low][k]] < level[sparse[low + l - (1 << k)][k]])
        return sparse[low][k];
    else return sparse[low + l - (1 << k)][k];
}

inline int LCA(int node1, int node2) {
    int aux;
    int x = firstOccurence[node1];
    int y = firstOccurence[node2];
    if(x > y) {
        aux = x;
        x = y;
        y = aux;
    }
    return euler[RMQ(x,y)];
}

int main() {
    int i, x, y;
    FILE* fin, *fout;
    fin = fopen("lca.in","r");
    fout = fopen("lca.out","w");
    fscanf(fin,"%d%d",&n,&m);
    for(i = 2; i <= n; i++) {
        fscanf(fin,"%d",&x);
        g[x].push_back(i);
    }
    DFS(1,0);
    preprocess(k);
    for(i = 0; i < m; i++) {
        fscanf(fin,"%d%d",&x,&y);
        fprintf(fout,"%d\n",LCA(x,y));
    }
    fclose(fin);
    fclose(fout);
    return 0;
}