Cod sursa(job #2454387)

Utilizator Tudor06MusatTudor Tudor06 Data 8 septembrie 2019 11:17:25
Problema Heapuri Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.72 kb
#include <iostream>
#include <stdio.h>

using namespace std;

int heap[200000];
int poz[200000];
int pozdepoz[200000];

void update( int cf, int n, int a ) {
  heap[cf] = a;
  poz[cf] = n;
  pozdepoz[poz[cf]] = cf;
  cf ++;
  int i = cf - 1;
  while ( ( i - 1 ) / 2 > 0 && heap[i] < heap[( i - 1 ) / 2] ) {
    swap( heap[i], heap[( i - 1 ) / 2] );
    swap( poz[i], poz[( i - 1 ) / 2] );
    swap( pozdepoz[i], pozdepoz[( i - 1 ) / 2] );
    i = ( i - 1 / 2 );
  }
}

void heap_remove( int cf, int a ) {
  int pz = pozdepoz[a - 1];
  while ( pz * 2 + 2 < cf ) {
    if ( heap[pz * 2 + 1] < heap[pz * 2 + 2] ) {
      swap( heap[pz], heap[pz * 2 + 1] );
      swap( poz[pz], poz[pz * 2 + 1] );
      swap( pozdepoz[pz], pozdepoz[pz * 2 + 1] );
      pz = pz * 2 + 1;
    } else {
      swap( heap[pz], heap[pz * 2 + 2] );
      swap( poz[pz], poz[pz * 2 + 2] );
      swap( pozdepoz[pz], pozdepoz[pz * 2 + 2] );
      pz = pz * 2 + 2;
    }
  }
  if ( pz * 2 + 1 < cf ) {
    swap( heap[pz], heap[pz * 2 + 1 ] );
    swap( poz[pz], poz[pz * 2 + 1] );
    swap( pozdepoz[pz], pozdepoz[pz * 2 + 1] );
  }
  cf --;

}
int main() {
  FILE *fin = fopen( "heapuri.in", "r" ), *fout = fopen( "heapuri.out", "w" );
  int n, cf, cfmax, a, cer;
  fscanf( fin, "%d", &n );
  cf = cfmax = 0;
  for ( int i = 0; i < n; i ++ ) {
    fscanf( fin, "%d", &cer );
    switch ( cer ) {
    case 1:
      fscanf( fin, "%d", &a );
      update( cf, cfmax, a );
      cfmax ++;
      cf ++;
      break;
    case 2:
      fscanf( fin, "%d", &a );
      heap_remove( cf, a );
      cf --;
      break;
    case 3:
      fprintf( fout, "%d\n", heap[0] );
    }
  }
  fclose( fin );
  fclose( fout );
  return 0;
}