Cod sursa(job #1414633)

Utilizator irimiecIrimie Catalin irimiec Data 2 aprilie 2015 20:29:18
Problema Lowest Common Ancestor Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.63 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

#ifndef ONLINE_JUDGE
ifstream fin("lca.in");
ofstream fout("lca.out");
#endif

const int MAXN = 100010;
const int LOGN = 18;
int n, m, s;
int lft[MAXN];
int lin[(MAXN << 4)][LOGN];
vector<int> vec[MAXN], h;

void euler(int nod, int niv) {
    lft[nod] = h.size();
    lin[h.size()][0] = nod;
    h.pub(niv);
    for(auto it : vec[nod]) {
        euler(it, niv + 1);
        lin[h.size()][0] = nod;
        h.pub(niv);
    }
}

void read() {
	fin >> n >> m;
	int x;

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

	euler(1, 0);
	s = h.size();

	for(int i = 1; (1 << i) <= s; ++i) {
        for(int j = 0; j + (1 << i) - 1 < s; ++j) {
            lin[j][i] = min(lin[j][i-1], lin[j + (1 << (i-1))][i-1]);
        }
	}

	int a, b, k;
	while(m--) {
        fin >> a >> b;
        a = lft[a]; b = lft[b];
	    if(a > b)
	        swap(a, b);

        k = int(log2(b - a + 1));
        fout << min(lin[a][k], lin[b - (1 << k) + 1][k]) << "\n";
	}
}

int main() {
	read();

    return 0;
}