Cod sursa(job #2330236)

Utilizator YouDontNeedMyNameJurcut Paul YouDontNeedMyName Data 28 ianuarie 2019 09:37:56
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.32 kb
#include <bits/stdc++.h>
#define N_MAX 100005
using namespace std;
ifstream in("lca.in");
ofstream out("lca.out");
vector <int> lista[N_MAX];
vector <int> e;
int n,nr,nivel[N_MAX],h[N_MAX];
bool ap[N_MAX];
int arb[21][4*N_MAX];
void dfs(int node)
{
    e.push_back(node);
    ap[node]=1;
    for(auto x:lista[node])
    {
        if(!ap[x])
        {
            dfs(x);
            e.push_back(node);
        }
    }
}
deque <int> q;
void bfs()
{
    q.push_back(1);
    nivel[1]=1;
    while(!q.empty())
    {
        int nod=q.front();
        q.pop_front();
        for(auto x:lista[nod])
        {
            if(!nivel[x])
            {
                q.push_back(x);
                nivel[x]=nivel[nod]+1;
            }
        }
    }
}
void rmq()
{
    for(int i=0; i<nr; i++)
    {
        arb[0][i]=i;
    }
    int put=1;
    for(int i=1; put<nr; i++)
    {
        for(int j=0; j<nr-put; j++)
        {
            if(nivel[e[arb[i-1][j]]]>nivel[e[arb[i-1][j+put]]])
            {
                arb[i][j]=arb[i-1][j+put];
            }
            else
            {
                arb[i][j]=arb[i-1][j];
            }
            //cout << arb[i][j] << ' ';
        }
        //cout << '\n';
        put*=2;
    }
}
int inlog(int x)
{
    int nr=0;
    while(x)
    {
        nr++;
        x/=2;
    }
    return nr-1;
}
int put(int x)
{
    if(x==0)
        return 1;
    if(x==1)
        return 2;
    int aux=put(x/2);
    if(x%2)
        return aux*aux*2;
    return aux*aux;
}
int lca(int a, int b)
{
    a=h[a];
    b=h[b];
    if(a>b)
        swap(a,b);
    int u=inlog(b-a+1);
    int no=put(u);
    if(nivel[e[arb[u][a]]]<nivel[e[arb[u][b-no+1]]])
    {
        return e[arb[u][a]];
    }
    return e[arb[u][b-no+1]];
}
int main()
{
    int o;
    in >> n >> o;
    h[1]=-1;
    for(int i=2; i<=n; i++)
    {
        h[i]=-1;
        int x;
        in >> x;
        lista[x].push_back(i);
    }
    dfs(1);
    bfs();
    nr=e.size()-1;
    for(int i=0; i<nr; i++)
    {
        //cout << e[i] << ' ';
        if(h[e[i]]==-1)
            h[e[i]]=i;
    }
    //cout << '\n';
    rmq();
    for(int i=0; i<o; i++)
    {
        int a,b;
        in >> a >> b;
        out << lca(a,b) << '\n';
    }
    return 0;
}