Cod sursa(job #2812503)

Utilizator iancupoppPopp Iancu Alexandru iancupopp Data 4 decembrie 2021 17:01:34
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.44 kb
#include <fstream>
#include <vector>

using namespace std;

const int N = 2e5 + 5;

class Heap {
private:
  vector<int> v, h;
  int p[N];
public:
  Heap() {
    v.push_back(0);
    h.push_back(0);
  }
  void up(int pos) {
    while (pos > 1 && v[h[pos]] < v[h[pos / 2]]) {
      swap(h[pos], h[pos / 2]);
      p[h[pos]] = pos;
      p[h[pos / 2]] = pos / 2;
      pos /= 2;
    }
  }
  void down(int pos) {
    while (pos * 2 < h.size()) {
      int fiu = pos * 2;
      if (pos * 2 + 1 < h.size() && v[h[pos * 2 + 1]] < v[h[fiu]])
        fiu = pos * 2 + 1;
      if (v[h[pos]] <= v[h[fiu]])
        break;
      swap(h[pos], h[fiu]);
      p[h[pos]] = pos;
      p[h[fiu]] = fiu;
      pos = fiu;
    }
  }
  int top() {
    return v[h[1]];
  }
  void insert(int x) {
    v.push_back(x);
    int pos = v.size() - 1;
    h.push_back(pos);
    p[pos] = h.size() - 1;
    up(p[pos]);
  }
  void erase(int pos) {
    pos = p[pos];
    swap(h[pos], h.back());
    p[h[pos]] = pos;
    h.pop_back();
    if (pos < h.size()) {
      up(pos);
      down(pos);
    }
  }
};

int main() {
  ifstream cin("heapuri.in");
  ofstream cout("heapuri.out");
  int t;
  Heap h;
  cin >> t;
  while (t--) {
    int cer;
    cin >> cer;
    if (cer == 1) {
      int x;
      cin >> x;
      h.insert(x);
    } else if (cer == 2) {
      int x;
      cin >> x;
      h.erase(x);
    } else {
      cout << h.top() << "\n";
    }
    int a = 1;
  }
  cin.close();
  cout.close();
  return 0;
}