Cod sursa(job #2757925)

Utilizator euyoTukanul euyo Data 7 iunie 2021 17:31:39
Problema Heapuri Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.4 kb
#include <fstream>

using namespace std;

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

const int MAXH = 200002;

struct H {
  int val;
  int t;
} heap[MAXH];

int p[MAXH];
int indH, tm = 1;

inline void swp( int a, int b ) {
  H aux;
  aux = heap[a], heap[a] = heap[b], heap[b] = aux;
  p[heap[a].t] = a;
  p[heap[b].t] = b;
}

void repairUp( int node ) {
  while ( node > 1 && heap[node].val < heap[node / 2].val ) {
	swp( node, node / 2 );
	node >>= 1;
  }
}
void repairDown( int node ) { 
  int minSon;	
 
  while ( 2 * node < indH ) {
    if ( heap[2 * node].val < heap[2 * node + 1].val ) {
      minSon = 2 * node;
	} else {
      minSon = 2 * node + 1;
	}
	if ( heap[node].val < heap[minSon].val ) {
	  swp( minSon, node );
	  node = minSon;
	} else {
	  node = indH;
	}
  }
  if ( 2 * node == indH && heap[node].val > heap[2 * node].val ) {
    swp( node, 2 * node );
  }
}
void add( int value ) {
  p[tm++] = ++indH;
  heap[indH] = { value, tm - 1 };
  repairUp( indH );
}
void cut( int t ) {
  int node = p[t];
  
  swp( indH, node );
  --indH;
  repairUp( node );
  repairDown( node );
}

int main() {
  int n, i, type, x;
  
  fin >> n;
  for ( i = 0; i < n; ++i ) {
	fin >> type;
	switch ( type ) {
	case 1:
	  fin >> x;
	  add( x );
	  break;
    case 2:
      fin >> x;
	  cut( x );
	  break;
	case 3:
	  fout << heap[1].val << "\n";
	  break;
	}
  }
  fin.close();
  fout.close();
  return 0;
}