Cod sursa(job #2340063)

Utilizator alex.cojocaruAlex Cojocaru alex.cojocaru Data 9 februarie 2019 18:49:03
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.6 kb
#include <iostream>
#define NMAX 200000
#define STVAL 100000000
using namespace std;


int poz [ NMAX + 5 ] ; /// poz[i] = al catelea nr. initial era val[i]
int pozinit [ NMAX + 5 ] ; /// pozinit[i] = pe ce pozitie in heap este al i-lea nr.
int val [ NMAX + 5 ] ;
int aux ;

class Heap {
public :
  int n = 1 ;
  void initializare () {
    int i ;
    for (i = 0 ; i <= NMAX ; i++ ) {
      val[i] = STVAL ;
      poz[i] = 0 ;
      pozinit[i] = 0 ;
    }
  }
  void sift (int k ) {
    int son, lson, rson ;
    do {
      lson = 2 * k ;
      rson = 2 * k + 1 ;
      if (lson <= n && val[lson] < val[rson] )
        son = lson ;
      else
        son = rson ;
      if (rson <= n && val[son] < val[k] ) {
        aux = val[son] ;
        val[son] = val[k] ;
        val[k] = aux ;
        pozinit[poz[son]] = k;
        pozinit[poz[k]] = son ;
        aux = poz[son] ;
        poz[son] = poz[k] ;
        poz[k] = aux ;
      }
      else
        son = 0 ;
    } while (son != 0 ) ;
  }
  void percolate (int k ) {
    int father ;
    father = k / 2 ;
    while (val[father] > val[k] && k > 1 ) {
      aux = val[father] ;
      val[father] = val[k] ;
      val[k] = aux ;
      pozinit[poz[father]] = k;
      pozinit[poz[k]] = father ;
      aux = poz[father] ;
      poz[father] = poz[k] ;
      poz[k] = aux ;
      k = father ;
      father = k / 2 ;
    }
  }
  void build_heap () {
    int i ;
    for (i = n/2 ; i > 0 ; i-- )
      sift (i) ;
  }
  void insertelem (int x, int nr ) {
    poz[n] = nr ;
    pozinit[nr] = n ;
    val[n++] = x ;
    percolate(n-1) ;
  }
  void cutelem (int x ) {
    int k = pozinit[x], father ;
    val[k] = val[n-1] ;
    poz[k] = poz[n-1] ;
    pozinit[x] = -1 ;
    pozinit[poz[k]] = k ;
    n--;
    father = k / 2 ;
    if (k > 1 && (val[k] < val[father] ) )
      percolate(k) ;
    else
      sift(k) ;
  }
};

Heap h ;

int main() {

  FILE *fin, *fout ;
  fin = fopen ("heapuri.in", "r" ) ;
  fout = fopen ("heapuri.out", "w" ) ;
  int n, i, tip, elem, elemente ;
  fscanf (fin, "%d", &n ) ;
  h.initializare() ;
  elemente = 1 ;
  for (i = 0 ; i < n ; i++ ) {
    fscanf (fin, "%d", &tip ) ;
    switch (tip) {
      case 1 : {
        fscanf (fin, "%d", &elem ) ;
        h.insertelem(elem, elemente) ;
        elemente++;
        break ;
      }
      case 2 : {
        fscanf (fin, "%d\n", &elem ) ;
        h.cutelem(elem) ; /// elementul intrat al x ulea
        break ;
      }
      case 3 : {
        fprintf (fout, "%d\n", val[1] ) ;
        break ;
      }
    }
  }
  return 0;
}