Cod sursa(job #2004218)

Utilizator Stefan_RaduStefan Radu Stefan_Radu Data 25 iulie 2017 12:11:16
Problema Heapuri Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.66 kb
#include <fstream>
#include <vector>
#include <bitset>

using namespace std;

ifstream cin("heapuri.in");
ofstream cout("heapuri.out");
const int MAX = 200005;
bitset< MAX > used;

class min_Heap {
public:
  min_Heap() {
    this -> heap.resize(MAX);
    this -> v.resize(MAX);
    this -> size = 0;
  }

  bool empty() {
    return size == 0;
  }

  int top() {
    return this -> v[heap[1]];
  }

  void insert(int n) {
    v[++ size] = n;
    heap[size] = size;
    m_insert(size);
  }

  void erase(int n) {
    used[n] = true;
  }

  void printMin() {
    while(used[heap[1]]) {
      m_erase();
    }
    cout << this -> top() << '\n';
  }
  
private:
  vector< int > v;
  vector< int > heap;
  int size;

  void m_insert(int poz) {
    if(v[heap[poz]] >= v[heap[poz >> 1]]) {
      return;
    }
    swap(heap[poz], heap[poz >> 1]);
    poz >>= 1;
    m_insert(poz);
  }

  void m_fix(int poz = 1) {
    if((v[heap[poz]] <= v[heap[poz << 1]] and v[heap[poz]] <= v[heap[poz << 1 | 1]]) or 
      (poz << 1) > this -> size) {
      return;
    }
    if(v[heap[poz]] > v[heap[poz << 1]]) {
      swap(heap[poz], heap[poz << 1]);
      m_fix(poz << 1);
    }
    else if((poz << 1 | 1) <= this -> size){
      swap(heap[poz], heap[poz << 1 | 1]);
      m_fix(poz << 1 | 1);
    }
  }

  void m_erase() {
    swap(heap[1], heap[this -> size --]);
    m_fix();
  }
};

int main() {
  int n;
  cin >> n;
  min_Heap* h = new min_Heap();

  while(n --) {
    int type;
    cin >> type;
    if(type == 3) {
      h -> printMin();
    }
    if(type != 3) {
      int k;
      cin >> k;
      if(type == 1) {
        h -> insert(k);
      }
      else {
        h -> erase(k);
      }
    }
  }

  return 0;
}