Cod sursa(job #2376818)

Utilizator vlad.ulmeanu30Ulmeanu Vlad vlad.ulmeanu30 Data 8 martie 2019 17:54:41
Problema Lowest Common Ancestor Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.5 kb
#include <bits/stdc++.h>
#define maxn 100000
#define pii pair<int,int>
#define fi first
#define se second

using namespace std;

vector <int> g[maxn+5];
vector <pii> eul; /// fi nod repr euler se nivel
int dp[20][4*maxn+5];
int fapr[maxn+5];

void dfs ( int nod, int niv )
{
  int i;
  eul.push_back ({nod,niv});
  for ( i = 0; i < g[nod].size(); i++ )
  {
    dfs ( g[nod][i], 1 + niv );
    eul.push_back ({nod,niv});
  }
}

int getl2 ( int n, int pin )
{
  int l2 = log(n) / log(2);
  l2 += ((1<<l2)<n && pin);
  return l2;
}

int rmq ( int lo, int hi )
{
  int l2 = getl2 ( hi - lo + 1, 0 );
  if ( eul[dp[l2][lo]].se < eul[dp[l2][hi-(1<<l2)+1]].se ) return dp[l2][lo];
  return dp[l2][hi-(1<<l2)+1];
}

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

  int n, t; fin >> n >> t;

  int i, j, x, es;
  for ( i = 1; i < n; i++ ) fin >> x, g[x-1].push_back(i);
  dfs(0,0);
  for ( i = 0; i < n; i++ ) fapr[i] = -1;
  es = eul.size();
  for ( i = 0; i < es; i++ )
    if ( fapr[eul[i].fi] == -1 ) fapr[eul[i].fi] = i;

  for ( i = 0; i < es; i++ ) dp[0][i] = i;
  int l2 = getl2 ( es, 1 );
  for ( i = 1; i <= l2; i++ )
    for ( j = 0; j < es - (1<<i) + 1; j++ )
      if ( eul[dp[i-1][j]].se < eul[dp[i-1][j+(1<<(i-1))]].se ) dp[i][j] = dp[i-1][j];
      else dp[i][j] = dp[i-1][j+(1<<(i-1))];
  int a, b;
  while(t--) fin >> a >> b, fout << eul[rmq( fapr[a-1], fapr[b-1] )].fi + 1 << '\n';

  fin.close ();
  fout.close ();

  return 0;
}