Cod sursa(job #1478566)

Utilizator daniel.grosuDaniel Grosu daniel.grosu Data 28 august 2015 23:29:55
Problema Lowest Common Ancestor Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.46 kb
#define REP(a,b) for(int a=0; a<(b); ++a)
#define REP2(a,b) for(int a=1; a<=(b); ++a)
#define FWD(a,b,c) for(int a=(b); a<(c); ++a)
#define BCK(a,b,c) for(int a=(b)-1; a>=(c); --a)
#define BCK2(a,b,c) for(int a=(b); a>(c); --a)
#define FWDS(a,b,c,d) for(int a=(b); a<(c); a+=d)
#define ALL(a) (a).begin(), (a).end()
#define SIZE(a) ((int)(a).size())
#define VAR(x) #x ": " << x << " "
#define FILL(x,y) memset(x,y,sizeof(x))
#define MIN(a,b) (((a)<(b))?(a):(b))
#define MAX(a,b) (((a)>(b))?(a):(b))
#define FAST ios_base::sync_with_stdio(0);cin.tie(0);
#define x first
#define y second
#define st first
#define nd second
#define mp make_pair
#define pb push_back
#define l(n) (n<<1)
#define r(n) ((n<<1)+1)
#define f(n) (n>>1)
#define lsb(a) (a&-a)

#include<vector>
#include<stack>
#include<queue>
#include<algorithm>

using namespace std;
#ifndef ONLINE_JUDGE
#include<fstream>
ifstream cin("lca.in");
ofstream cout("lca.out");
#else
#include<iostream>
#endif

const int NMAX = 100069;
const int PMAX = 1015;
const int INF = 1 << 31;
const int dx[] = {0, 0, -1, 1}; //1,1,-1,1};
const int dy[] = {-1, 1, 0, 0}; //1,-1,1,-1};

typedef long long LL;
typedef pair<int, int> PII;
typedef long double K;
typedef pair<K, K> PKK;
typedef vector<int> VI;

int x,y;

int a,b,sol,p;

int n,m;

int s[NMAX], v;
int h[NMAX<<1], k;
int d[NMAX<<1];
int pos[NMAX];
int Log[NMAX], rmq[21][NMAX];

VI G[NMAX];

void dfs(int i, int lvl)
{
    // log in
    h[++k]=i;
    d[k]=lvl;
    
    pos[i]=k;
    
    REP(j,G[i].size())
    {
        dfs(G[i][j], lvl+1);
    
        // log in
        h[++k]=i;
        d[k]=lvl;
    }
}

int main(){
    FAST;
    cin>>n>>m;
    for(int i=2; i<=n; ++i)
        cin>>x,
        G[x].push_back(i);
    
    // DFS to construct the Euler traversal in h[k].
    dfs(1,0);
    
    // RMQ preprocessing
    for(int i=2; i<=k; ++i)
        Log[i]=Log[i>>1] + 1;
    for(int i=1; i<=k; ++i)
        rmq[0][i]=i;
    for(int i=1; (1<<i) < k; ++i)
        for(int j=1; j + (1<<i) <= k; ++j){
            rmq[i][j]=rmq[i-1][j];
            if(d[rmq[i-1][j+(1<<(i-1))]]< d[rmq[i][j]])
                rmq[i][j]=rmq[i-1][j+(1<<(i-1))];
        }
    //Respond to queries:
    REP(i,m)
    {
        cin>>x>>y;
        a=pos[x], b=pos[y]; b++; // increment so it will be inclusive: [a,b]
        if(a>b)
            swap(a,b);
        p=Log[b-a];
        sol=rmq[p][a];
        if(d[sol] > d[rmq[p][b-(1<<p)]])
            sol=rmq[p][b-(1<<p)];
        cout<<h[sol]<<"\n";
    }
    
    return 0;
}