Cod sursa(job #2004266)

Utilizator Stefan_RaduStefan Radu Stefan_Radu Data 25 iulie 2017 13:47:56
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.94 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 -> heap_size = 0;
    this -> v_size = 0;
  }

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

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

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

  void printMin() {
    if(!used[heap[1]]) {
      cout << this -> top() << '\n';
      return;
    }
    m_erase();
    printMin();
  }
private:

  vector< int > v;
  vector< int > heap;
  int v_size;
  int heap_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((poz << 1 | 1) <= this -> heap_size) {
      if((v[heap[poz]] <= v[heap[poz << 1]] and v[heap[poz]] <= v[heap[poz << 1 | 1]])) {
        return;
      }

      if(v[heap[poz << 1]] <= v[heap[poz << 1 | 1]]) {
          swap(heap[poz], heap[poz << 1]);
          m_fix(poz << 1);
      }
      else {
          swap(heap[poz], heap[poz << 1 | 1]);
          m_fix(poz << 1 | 1);
      }
    }
    else if((poz << 1) <= this -> heap_size) {
      if(v[heap[poz]] <= v[heap[poz << 1]]) {
        return;
      }

      swap(heap[poz], heap[poz << 1]);
      m_fix(poz << 1);
    }
    else {
      return;
    }
  }

  void m_erase() {
    swap(heap[1], heap[this -> heap_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();
    }
    else {
      int k;
      cin >> k;
      if(type == 1) {
        h -> insert(k);
      }
      else {
        h -> erase(k);
      }
    }
  }

  return 0;
}