Cod sursa(job #1075312)

Utilizator Iustin_BulimarFMI Iustin Bulimar Iustin_Bulimar Data 8 ianuarie 2014 20:49:02
Problema Lowest Common Ancestor Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.11 kb
#include <fstream>
#include <vector>
using namespace std;
ifstream cin("lca.in");
ofstream cout("lca.out");

const int n_max=100001;
const int log_n_max=17;

vector<int> a[n_max];
int n, q, i, x, y, k, niv, nivel[n_max], ord[n_max], p[n_max], m[n_max][log_n_max];

void dfs(int nod, int niv)
{
    int i;
    ord[++k]=nod;
    nivel[k]=++niv;
    p[nod]=k;
    for(i=1; i<=a[nod].size(); i++) dfs(a[nod][i], niv);
}

int loga(int a)
{
    int i;
    for(i=1; 1<<i<=a; i++);
    return --i;
}

bool comp(int a, int b)
{
    return (nivel[p[a]]<nivel[p[b]]);
}

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

int main()
{
    cin>>n>>q;
    for(i=1; i<n; i++)
    {
        cin>>x;
        a[x].push_back(i);
    }
    dfs(1, 0);
    rmq();
    while(q--)
    {
        cin>>x>>y;
        if(x>y) swap(x, y);
        k=loga(y-x+1);
        cout<<ord[min(nivel[p[m[x-1][k]]], nivel[p[m[y-(1<k)][k]]])]<<'\n';
    }
    return 0;
}