Cod sursa(job #673586)

Utilizator Eugen01Vasilescu Eugen Eugen01 Data 4 februarie 2012 17:34:40
Problema Lowest Common Ancestor Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.16 kb
#include<stdio.h>
#include<vector>
#define Nmax 100009
#define pb push_back
#define min(a,b) ((a<b)?a:b)

using namespace std;

int log,nr,x,y,n,t,i,j,first[Nmax],MIN[25][2*Nmax];
vector<int> Q,a[Nmax];
vector<int>::iterator it;

void euler(int nod)
{
    Q.pb(nod);
    if (!first[nod]) first[nod]=Q.size()-1;
    for (vector<int>::iterator it=a[nod].begin();it!=a[nod].end();it++)
    {
        euler(*it);
        Q.pb(nod);
    }
}

void RMQ()
{
    nr=Q.size();
    for (log=0;(1<<(log+1))<=nr;log++);

    for (i=0;i<nr;i++) MIN[0][i]=Q[i];

    for (i=1;i<=log;i++)
        for (j=0;j<nr-(1<<(i-1));j++)
            MIN[i][j]=min(MIN[i-1][j],MIN[i-1][j+(1<<(i-1))]);
}
int main()
{
    freopen("lca.in","r",stdin);
    freopen("lca.out","w",stdout);

    scanf("%d%d",&n,&t);
    for (i=2;i<=n;i++)
    {
        scanf("%d",&x);
        a[x].pb(i);
    }
    euler(1);
    RMQ();
    for (i=1;i<=t;i++)
    {
        scanf("%d%d",&x,&y);
        x=first[x];
        y=first[y];
        if (x>y) swap(x,y);
        for (log=0;(1<<(log+1))<=y-x;log++);
        printf("%d\n",min(MIN[log][x],MIN[log][y-(1<<log)+1]));
    }
}