Cod sursa(job #1895347)

Utilizator NoSwearFlorea Marian NoSwear Data 27 februarie 2017 21:59:31
Problema Lowest Common Ancestor Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.36 kb
#include<fstream>
#include<vector>
#define NMAX 100005
using namespace std;
ifstream cin("rmq.in");
ofstream cout("rmq.out");
int n, m, x, y, i, j, lungime;
int d[17][NMAX], first[NMAX];
int p, nn;
vector<int> G[NMAX];
void euler(int nod)
{
    d[0][++nn] = nod;
    if(first[nod] == 0)
    {
        first[nod] = nn;
    }
    for(int i = 0; i < G[nod].size(); i++)
    {
        int fiu = G[nod][i];
        euler(fiu);
        d[0][++nn] = nod;
    }
}
int putere(int lungime)
{
    int p = 0;
    while((1 << p) < lungime)
    {
        p++;
    }
    p--;
    return p;
}
int main()
{
    cin >> n >> m;
    for(int i = 2; i <= n; i++)
    {
        cin >> x;
        G[x].push_back(i);
    }
    euler(1);
    for(i = 1; (1 << i) <= nn; i++)
    {
        for(j = 1; j <= nn; j++)
        {
            d[i][j] = min(
            d[i - 1][j],
            d[i - 1][j + (1 << (i - 1))]);
        }
    }

    while(m--)
    {
        cin >> x >> y;
        x = first[x];
        y = first[y];
        if(x > y)
        {
            swap(x, y);
        }
        lungime = y - x + 1;
        p = putere(lungime);
        cout << min(d[p][x],
        d[p][y - (1 << p) + 1]) << "\n";
    }
    return 0;
}