Cod sursa(job #2572956)

Utilizator RazvanPanaiteRazvan Panaite RazvanPanaite Data 5 martie 2020 15:08:42
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.8 kb
#include <bits/stdc++.h>
#define pb push_back

using namespace std;

ifstream fin("lca.in");
ofstream fout("lca.out");

void debug_out() { cerr << '\n'; }
template <typename Head, typename... Tail> void debug_out(Head H, Tail... T) { cerr << " " << H; debug_out(T...);}
#define dbg(...) cerr << #__VA_ARGS__ << " ->", debug_out(__VA_ARGS__)
#define dbg_v(x, n) do{cerr<<#x"[]: ";for(int _=0;_<n;++_)cerr<<x[_]<<" ";cerr<<'\n';}while(0)
#define dbg_ok cerr<<"OK!\n"

typedef pair<int,int> pii;
typedef long long int ll;
typedef long double ld;

const int DMAX = 1e5+10;
const int LogMAX = 25;

int n,q,cnt;

vector <int> arb[DMAX];

int euler[2*DMAX];
int nivel[DMAX];
int ap[DMAX];
int dp[2*DMAX][LogMAX];

void dfs(int node);
void constr();

int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(0);

    int t,i,j;
    int x,y,k;

    fin>>n>>q;
    for(i=2;i<=n;i++){
        fin>>x;
        arb[x].pb(i);
    }
    nivel[1]=0;
    dfs(1);
    constr();
    while(q--){
        fin>>x>>y;
        x=ap[x];
        y=ap[y];
        if(x > y)
            swap(x,y);
        k=log2(y-x+1);
        if(nivel[dp[x][k]] < nivel[dp[y-(1<<k)+1][k]])
            fout<<dp[x][k]<<'\n';
        else
            fout<<dp[y-(1<<k)+1][k]<<'\n';
    }

    return 0;
}
void dfs(int node){
    euler[++cnt]=node;
    ap[node]=cnt;
    for(auto& it:arb[node]){
        nivel[it]=nivel[node]+1;
        dfs(it);
        euler[++cnt]=node;
    }
}
void constr(){
    int i,j;
    for(i=1;i<=cnt;i++)
        dp[i][0]=euler[i];
    for(j=1;(1<<j) <= cnt;j++)
        for(i=1;i+(1<<j)-1 <= cnt;i++)
            if(nivel[dp[i][j-1]] < nivel[dp[i+(1<<(j-1))][j-1]])
                dp[i][j]=dp[i][j-1];
            else
                dp[i][j]=dp[i+(1<<(j-1))][j-1];
}