Cod sursa(job #2474652)

Utilizator Asgari_ArminArmin Asgari Asgari_Armin Data 15 octombrie 2019 17:54:39
Problema Lowest Common Ancestor Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.56 kb
#include <fstream>
#include <vector>
#include <bitset>
using namespace std;

ifstream fin( "lca.in" );
ofstream fout( "lca.out" );
const int NMAX = 100000;
vector <int> v[NMAX + 1];
vector <int> sir;
bitset <NMAX + 2> viz;
int h[100002];
int lg[NMAX + 2];
int first[NMAX + 2];
int rmq[(NMAX << 1) + 2][18];
void dfs( int nod ){
  int i;
  viz[nod] = 1;
  first[nod] = sir.size();
  sir.push_back(nod);
  for( i = 0; i < v[nod].size(); ++i )
    if( !viz[v[nod][i]] )
    {
      h[v[nod][i]] = h[nod] + 1;
      dfs( v[nod][i] );
      sir.push_back(nod);
    }
}

int main() {
    int n, q, i, a, k, b, dif;
    fin >> n >> q;
    for( i = 2; i <= n; ++i ){
      fin >> a;
      v[a].push_back(i);
    }
    dfs(1);
    for( i = 0; i < n + n - 2; ++i )
      rmq[i][0] = sir[i];
    for( i = 2; i <= n; ++i )
      lg[i] = lg[i >> 1] + 1;
    for( k = 1; k <= 17; ++k )
      for( i = 0; i < n + n - 2 - (1 << k) + 1; ++i )
        if( h[rmq[i][k - 1]] < h[rmq[i + (1 << (k - 1))][k - 1]] )
          rmq[i][k] = rmq[i][k - 1];
        else
          rmq[i][k] = rmq[i + (1 << (k - 1))][k - 1];
    while( q-- ){
      fin >> a >> b;
      if( first[a] > first[b] )
        swap(a, b);
      b=first[b];
      a=first[a];
      dif = b - a + 1;
      if( h[rmq[a][lg[dif]]] < h[rmq[b - (1 << lg[dif]) + 1][lg[dif]]])
        fout << rmq[a][lg[dif]];
      else
        fout << rmq[b - (1 << lg[dif]) + 1][lg[dif]];
      fout << "\n";
    }
    //for( i = 0; i < sir.size(); ++i )
      //fout << sir[i] << " ";
    return 0;
}