Cod sursa(job #3130094)

Utilizator AnaRosuAna Maria Rosu AnaRosu Data 16 mai 2023 20:37:23
Problema Heapuri Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.38 kb
#include <iostream>
#include <vector>
#include <fstream>
#include <limits>
using namespace std;

ifstream f("heapuri.in");
ofstream g("heapuri.out");

class MinHeap {
private:
  int cnt = 0;
  vector<pair<int, int>> heap;
  vector<int> elem;
  vector<int> pos;

public:
  MinHeap() {
    heap = {};
    heap.push_back(make_pair(numeric_limits<int>::max(), 0));
    elem = {0};
    pos = {0};
  }

  void repairHeapDown(int poz) {
    if (2 * poz + 1 >= static_cast<int>(heap.size())) {
      return;
    }
    if (2 * poz + 2 == static_cast<int>(heap.size()) || heap[2 * poz + 1].first < heap[2 * poz + 2].first) {
      if (heap[2 * poz + 1].first < heap[poz].first) {
        swap(heap[2 * poz + 1], heap[poz]);
        swap(pos[heap[2 * poz + 1].second], pos[heap[poz].second]);
        repairHeapDown(2 * poz + 1);
        return;
      } else
        return;
    } else {
      if (heap[2 * poz + 2].first < heap[poz].first) {
        swap(heap[2 * poz + 2], heap[poz]);
        swap(pos[heap[2 * poz + 2].second], pos[heap[poz].second]);
        repairHeapDown(2 * poz + 2);
        return;
      } else
        return;
    }
  }

  void repairHeapUp(int poz) {
    while (poz) {
      int dad = (poz - 1) / 2;
      if (heap[dad].first > heap[poz].first) {
        swap(heap[dad], heap[poz]);
        swap(pos[heap[poz].second], pos[heap[dad].second]);
        poz = dad;
      } else
        break;
    }
  }

  void insert(int x) {
    elem.push_back(x);
    pos.push_back(++cnt);
    heap.push_back(make_pair(x, cnt));
    repairHeapUp(heap.size() - 1);
  }

  void del(int i) {
    if (i >= elem.size()) {
      return;  // Element not found
    }

    int idx = pos[i];
    if (idx == -1) {
      return;  // Element not found
    }

    pos[i] = -1;
    heap[idx] = make_pair(numeric_limits<int>::max(), idx);
    repairHeapDown(idx);
  }

  void mini() {
    g << heap.front().first << endl;
  }
};

int main() {
  MinHeap H;
  int n, a, b;
  f >> n;
  for (int i = 0; i < n; ++i) {
    f >> a;
    switch (a) {
      case 1: {
        f >> b;
        H.insert(b);
        break;
      }
      case 2: {
        f >> b;
        H.del(b);
        break;
      }
      case 3: {
        H.mini();
        break;
      }
      default: {
        break;
      }
    }
  }
  f.close();
  g.close();
  return 0;
}