Cod sursa(job #2454488)

Utilizator Tudor06MusatTudor Tudor06 Data 8 septembrie 2019 17:36:24
Problema Heapuri Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.01 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;
  int i = cf;
  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] );
    pozdepoz[poz[i]] = i;
    pozdepoz[poz[( i - 1 ) / 2]] = ( i - 1 ) / 2;
    i = ( i - 1 / 2 );
  }
  if ( heap[0] > heap[1] && cf > 1 ) {
    swap( heap[0], heap[1] );
    swap( poz[0], poz[1] );
    pozdepoz[poz[1]] = 1;
    pozdepoz[poz[0]] = 0;
  }
}

void heap_remove( int cf, int a ) {
  int pz = pozdepoz[a - 1];
  swap( heap[cf - 1], heap[pz] );
  cf --;
  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] );
      pozdepoz[poz[pz]] = pz;
      pozdepoz[poz[pz * 2 + 1]] = pz * 2 + 1;
      pz = pz * 2 + 1;
    } else {
      swap( heap[pz], heap[pz * 2 + 2] );
      swap( poz[pz], poz[pz * 2 + 2] );
      pozdepoz[poz[pz * 2 + 2]] = pz * 2 + 2;
      pozdepoz[poz[pz]] = pz;
      pz = pz * 2 + 2;
    }
  }
  if ( pz * 2 + 1 < cf ) {
    swap( heap[pz], heap[pz * 2 + 1 ] );
    swap( poz[pz], poz[pz * 2 + 1] );
    pozdepoz[poz[pz]] = pz;
    pozdepoz[poz[pz * 2 + 1]] = pz * 2 + 1;
  }
}
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] );
      break;
    }
  }
  fclose( fin );
  fclose( fout );
  return 0;
}