Cod sursa(job #1377692)

Utilizator corul_barbatescUNIBUC Kira96 lockmihai corul_barbatesc Data 5 martie 2015 23:47:26
Problema Lowest Common Ancestor Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.37 kb
/*
    Those without power, seek us!
    Those with power, fear us!
    We are the Order of the Black Knights!
*/

#include<fstream>
#include<cstdio>
#include<map>
#include<set>
#define FIT(a,b) for(vector<int >::iterator a=b.begin();a!=b.end();a++)
#define FITP(a,b) for(vector<pair<int,int> >::iterator a=b.begin();a!=b.end();a++)
#define RIT(a,b) for(vector<int>::reverse_iterator a=b.end();a!=b.begin();++a)
#include<stack>
#define ROF(a,b,c) for(int a=b;a>=c;--a)
#include<vector>
#include<algorithm>
#define FOR(a,b,c) for(int a=b;a<=c;++a)
#define REP(a,b) for(register int a=0;a<b;++a)
#include<cstring>
#include<ctime>
#include<bitset>
#include<cmath>
#include<iomanip>
#include<set>
#define f cin
#define g cout
#include<queue>
#define debug cerr<<"OK";
#define pii pair<int,int>
#define mp make_pair
#define pb push_back
#define fi first
#define se second
#define ll long long
#define ull unsigned int
#define mod 1000000009LL
#define SQR 350
#define db double
#define inf 1<<30
#define div fdasfasd
#define hash dsafdsfds
#define od 100003
#define mod 666013
#define DIM 60010000
#define base 256
#define bas 255
#define N 100100
#define inf 0x3f3f3f3f
using namespace std;
ifstream f("lca.in");
ofstream g("lca.out");
/*
    int dx[]={0,0,0,1,-1};
    int dy[]={0,1,-1,0,0};
*/
vector<int> v[N];
int E[N*2],r[18][N*2],lg[N*2],poz[N],niv[N],t,x,y,n,m;
void dfs(int x,int p,int lvl)
{
    E[++t]=x;
    poz[x]=t;
    niv[x]=lvl;
    FIT(it,v[x])
    if(!niv[*it])
    {
        dfs(*it,x,lvl+1);
        E[++t]=x;
    }
}
int main ()
{
    f>>n>>m;
    FOR(i,2,n)
    {
        f>>x;
        v[x].pb(i);
    }
    dfs(1,0,1);
    FOR(i,2,t)
    lg[i]=lg[i/2]+1;
    FOR(i,1,t)
    r[0][i]=E[i];
    for(int p=1,po=1;po<=t;po<<=1,++p)
        FOR(i,1,t)
        {
            if(i+po<=t)
            {
                r[p][i]=r[p-1][i];
                 if(niv[r[p-1][i+po]]<niv[r[p][i]])
                    r[p][i]=r[p-1][i+po];
            }
            else
                r[p][i]=r[p-1][i];
        }
    FOR(i,1,m)
    {
        f>>x>>y;
        x=poz[x];
        y=poz[y];
        if(x>y)
            swap(x,y);
        int dif=y-x+1;
        int p=lg[dif];
        int sol=r[p][x+dif-(1<<p)];
        if(niv[r[p][x]]<niv[sol])
            sol=r[p][x];
        g<<sol<<"\n";
    }
    return 0;
}