Cod sursa(job #2013406)

Utilizator Stefan_RaduStefan Radu Stefan_Radu Data 21 august 2017 13:11:39
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.18 kb
#include <fstream>
#include <vector>
#include <bitset>

using namespace std;

ifstream cin("heapuri.in");
ofstream cout("heapuri.out");

template < class Type >

class Heap {
public:
  
  Heap(): _MAX(250005) {
    this -> _arr.resize(_MAX);
    this -> _heap.resize(_MAX);
    this -> _arr_size = 0;
    this -> _heap_size = 0;
  }

  int size() {
    return _heap_size;
  }

  Type push(Type x) {
    _push(x);
  }

  Type pop(int x) {
    _poped[x] = true;
  }

  Type top() {
    while (_poped[_heap[1]]) {
      _pop();
    }
    for (int i = 1; i <= _heap_size; i ++) {
      cout << _arr[_heap[i]] << ' ';
    }
    cout << '\n';
    return _arr[_heap[1]];
  }
private:

  const int _MAX;
  vector < int > _heap;
  vector < Type > _arr;
  bitset < 250005 > _poped;	
  int _heap_size;
  int _arr_size;

  void _repair(int node) {
    if ((node << 1 | 1) <= _heap_size) {
      if (_arr[_heap[node]] > min(_arr[_heap[node << 1]], _arr[_heap[node << 1 | 1]])) {
        if (_arr[_heap[node << 1]] <= _arr[_heap[node << 1 | 1]]) {
          swap(_heap[node], _heap[node << 1]);
          _repair(node << 1);
        }
        else {
          swap(_heap[node], _heap[node << 1 | 1]);
          _repair(node << 1 | 1);
        }
      }
      return;
    }
    else if ((node << 1) == _heap_size) {
      if (_arr[_heap[node]] > _arr[_heap[node << 1]]) {
        swap(_heap[node], _heap[node << 1]);
      }
      return;
    }
    else if (node << 1 > _heap_size) {
      return;
    }
  }

  void _pop() {
    swap(this -> _heap[1], this -> _heap[this -> _heap_size --]);
    this -> _repair(1);
  }

  void _set_poz(int node) {
    if (_arr[_heap[node]] >= _arr[_heap[node >> 1]] or node == 1) {
      return;
    }

    swap(_heap[node], _heap[node >> 1]);
    _set_poz(node >> 1);
  }

  void _push(Type x) {
    _arr[++ _arr_size] = x;
    _heap[++ _heap_size] = _arr_size;
    _set_poz(_heap_size);
  }
}; 

int main() {
  Heap < int > *h = new Heap < int >();

  int n; cin >> n;

  while (n --) {
    int cod; cin >> cod;
    if (cod == 1) {
      int x; cin >> x;
      h -> push(x);
    }
    else if (cod == 2) {
      int x; cin >> x;
      h -> pop(x);
    }
    else {
      cout << h -> top() << '\n';
    }
  }
}