Cod sursa(job #1400142)

Utilizator irimiecIrimie Catalin irimiec Data 25 martie 2015 09:31:26
Problema Lowest Common Ancestor Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.87 kb
#include <bits/stdc++.h>

using namespace std;

#define     mp              make_pair
#define     fs              first
#define     sc              second
#define     pob             pop_back
#define     pub             push_back
#define     eps             1E-7
#define     sz(a)           a.size()
#define     count_one       __builtin_popcount;
#define     count_onell     __builtin_popcountll;
#define     fastIO          ios_base::sync_with_stdio(false)
#define     PI              (acos(-1.0))
#define     linf            (1LL<<62)//>4e18
#define     inf             (0x7f7f7f7f)//>2e9

#define MAXN 100010
#define MAXL 25

#ifndef ONLINE_JUDGE
ifstream f("lca.in");
ofstream g("lca.out");
#endif

int n, m;
vector<int> child[MAXN];
vector<int> eul, height;
int lft[MAXN], rght[MAXN << 4];
int rmq[MAXN << 4][MAXL];
int Start, End, hsol, sol;

void euler(int nod, int h) {
    lft[nod] = eul.size();
    rght[eul.size()] = nod;
    eul.pub(nod);
    height.pub(h);
    for(auto it : child[nod]) {
        euler(it, h + 1);
        rght[eul.size()] = nod;
        eul.pub(nod);
        height.pub(h);
    }
}

void computeRMQ() {
    for(int i = 0; i < n; ++i)
        rmq[i][0] = eul[i];
    for(int j = 1; (1 << j) <= n; ++j)
        for(int i = 0; i + (1 << j) - 1 < n; ++i) {
            rmq[i][j] = min(rmq[i][j - 1], rmq[i + (1 << (j - 1))][j - 1]);
        }
}

int main() {
    f >> n >> m;

    int x;
    for(int i = 2; i <= n; ++i) {
        f >> x;
        child[x].pub(i);
    }

    euler(1, 0);
    n = eul.size();
    computeRMQ();

    int a, b;
    while(m--) {
        f >> a >> b;
        Start = lft[a]; End = lft[b];
        if(Start > End)
            swap(Start, End);
        int k = int(log2(End - Start + 1));
        g << min(rmq[Start][k], rmq[End - (1 << k) + 1][k]) << "\n";
    }
    return 0;
}