Cod sursa(job #2409511)

Utilizator isa_tudor_andreiAndrei Tudor isa_tudor_andrei Data 19 aprilie 2019 10:01:01
Problema Heapuri Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.11 kb
#include <bits/stdc++.h>
#define MAXN 200000

using namespace std;

int nh;
int h[MAXN+1], v[MAXN+1], poz[MAXN + 1];


void schimb( int p, int q ) {
  int aux = h[p];
  h[p] = h[q];
  h[q] = aux;
  poz[h[p]] = p;
  poz[h[q]] = q;
}

void urca( int p ) {
  while( p > 1 && v[h[p]] < v[h[p/2]] ) {
    schimb(p, p/2);
    p /= 2;
  }
}

void coboara( int p ) {
  int fs = 2 * p, fd = 2 * p + 1, bun = p;
  if( fs <= nh && v[h[fs]] < v[h[bun]] )
    bun = fs;
  if( fd <= nh && v[h[fd]] < v[h[bun]] )
    bun = fd;
  if( bun != p ) {
    schimb(p,bun);
    coboara(bun);
  }
}

void adauga( int i ) {
  h[nh] = i;
  poz[nh] = nh;
  urca(nh);
}

void sterge( int p ) {
  if( p == nh )
    nh --;
  else {
    schimb( p, nh -- );
    urca(p);
    coboara(p);
  }
}

int main() {
    ifstream fin("heapuri.in");
    ofstream fout("heapuri.out");
    int tip, x, i, n;
    fin>>n;
    for( i = 1; i <= n; i ++ ) {
      fin>>tip;
      if( tip == 1 ) {
        fin>>v[++nh];
        adauga(nh);
      }
      else if( tip == 2 ) {
        fin>>x;
        sterge(poz[x]);
      }
      else
        fout<<v[h[1]]<<"\n";
    }
    return 0;
}