Cod sursa(job #523286)

Utilizator andreitheo87Teodorescu Andrei-Marius andreitheo87 Data 17 ianuarie 2011 18:01:14
Problema Heapuri Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.43 kb
#include <fstream>
#include <iostream>
#include <string.h>

using namespace std;

int posHeap[200001];
int sizeHeap = 0;
int heap[200001]; // pozitii
int value[2000001]; // valori

void swap(int pos1, int pos2) {
  int aux = heap[pos1]; heap[pos1] = heap[pos2]; heap[pos2] = aux;
  posHeap[heap[pos1]] = pos1; posHeap[heap[pos2]] = pos2;
}

void insertHeap(int x, int poz) {
  value[poz] = x;
  sizeHeap++;
  heap[sizeHeap] = poz;
  posHeap[poz] = sizeHeap;
  int pos = sizeHeap;
  while (pos > 1 && value[heap[pos]] < value[heap[pos>>1]]) {
    swap(pos, pos>>1);
    pos = pos >> 1;
  }
}

void popx(int x) {
  int pos = posHeap[x];
  swap(posHeap[x], sizeHeap); sizeHeap--;
  while ((pos<<1) <= sizeHeap) {
    int posBest = pos<<1;
    if ((pos<<1) + 1 <= sizeHeap && value[heap[(pos<<1)+1]] < value[heap[pos<<1]])
      posBest = (pos<<1) + 1;
    if (value[heap[pos]] > value[heap[posBest]]) {
      swap(pos, posBest);
      pos = posBest;
    } else break;
  }
}

int get_min() {
	return value[heap[1]];
}

int main() {
  ifstream in("heapuri.in");
  ofstream out("heapuri.out");
  int nop;
  in >> nop;
  int pos = 1;
  for (int i=0; i<nop; i++) {
	  int op, x;
	  in >> op;
	  switch (op) {
		  case 1:
			  in >> x;
			  insertHeap(x, pos++);
			  break;
		  case 2:
			  in >> x;
			  popx(x);
			  break;
		  case 3:
			  out << get_min() << endl;
			  break;
	  }
  }
  return 0;
}