Cod sursa(job #3372384)

Utilizator maria.bertolonMaria Bertolon maria.bertolon Data 3 noiembrie 2026 14:43:11
Problema Heapuri Scor 100
Compilator c-64 Status done
Runda Arhiva educationala Marime 1.4 kb
#include <stdio.h>
#include <stdlib.h>

#define MAXN 200000

int heap[MAXN + 1], v[MAXN + 1], time[MAXN + 1];
int p;

void add( int x ){
  int aux;
  while( x > 1 && v[heap[x]] < v[heap[x / 2]] ){
    aux = heap[x];
    heap[x] = heap[x / 2];
    heap[x / 2] = aux;

    time[heap[x]] = x;
    time[heap[x / 2]] = x / 2;
    x /= 2;
  }
}

void del( int x ){
  int aux, y = 0;

  while( x != y ){
    y = x;
    if( y * 2 <= p && v[heap[x]] > v[heap[y * 2]] )
      x = y * 2;
    if( y * 2 + 1 <= p && v[heap[x]] > v[heap[y * 2 + 1]] )
      x = y * 2 + 1;

    aux = heap[x];
    heap[x] = heap[y];
    heap[y] = aux;

    time[heap[x]] = x;
    time[heap[y]] = y;
  }
}

int main(){
  FILE *fin, *fout;
  int q, c, x, t;

  fin = fopen( "heapuri.in", "r" );
  fout = fopen( "heapuri.out", "w" );

  fscanf( fin, "%d", &q );
  p = t = 0;
  while( q-- ){
    fscanf( fin, "%d", &c );
    if( c == 1 ){
      fscanf( fin, "%d", &x );

      p++;
      t++;

      heap[p] = t;
      v[t] = x;
      time[t] = p;

      add( p );
    }else if( c == 2 ){
      fscanf( fin, "%d", &x );

      v[x] = -1;
      add( time[x] );

      time[heap[1]] = 0;
      heap[1] = heap[p--];
      time[heap[1]] = 1;
      if( p > 1 )
        del( 1 );
    }else{
      fprintf( fout, "%d\n", v[heap[1]] );
    }
  }


  fclose( fin );
  fclose( fout );

  return 0;
}