Cod sursa(job #2883527)

Utilizator TeodorLuchianovTeo Luchianov TeodorLuchianov Data 1 aprilie 2022 16:22:04
Problema Heapuri Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.74 kb
#include <fstream>
#include <vector>

using namespace std;

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

int const NMAX = 200000;

int timeToNode[1 + NMAX], currentTime = 0;

class Heap {
private:
  vector <int> heap;
  vector <int> time;
public:

  Heap() {
    heap.push_back(0);
    time.push_back(0);
  }

  void swapNode(int node1, int node2) {
    timeToNode[time[node1]] = node2;
    timeToNode[time[node2]] = node1;
    swap(time[node1], time[node2]);
    swap(heap[node1], heap[node2]);
  }

  void up(int node) {
    if(node == 1) {
      return;
    }
    int parent = node / 2;
    if(heap[node] < heap[parent]){
      swapNode(node, parent);
      up(parent);
    }
  }

  void down(int node) {
    int left = 2 * node, right = 2 * node + 1;
    if(heap.size() <= left){
      return;
    }
    int child;
    if(heap.size() <= right || heap[left] < heap[right]){
      child = left;
    }else {
      child = right;
    }
    if(heap[child] < heap[node]){
      swapNode(child, node);
      down(child);
    }
  }

  void add(int value) {
    currentTime++;
    timeToNode[currentTime] = heap.size();
    time.push_back(currentTime);
    heap.push_back(value);
    up(heap.size() - 1);
  }
  void detach(int node) {
    swapNode(node, heap.size() - 1);
    heap.pop_back();
    up(node);
    down(node);
  }
  int root() {
    return heap[1];
  }
};

int main() {

  int t;
  in >> t;
  Heap heap;
  for(int q = 1;q <= t;q++) {
    int cer, c;
    in >> cer;
    if(cer == 1) {
      in >> c;
      heap.add(c);
    }else if(cer == 2) {
      in >> c;
      heap.detach(timeToNode[c]);
    }else {
      out << heap.root() << '\n';
    }
  }
  return 0;
}