Cod sursa(job #3236843)

Utilizator urweakurweak urweak Data 2 iulie 2024 23:12:27
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.55 kb
#include <iostream>
#include <vector>
#include <fstream>
#define MAXSIZE 200000

using namespace std;
ifstream fin("heapuri.in");
ofstream fout("heapuri.out");

class MinHeap{
private:
  int heap[MAXSIZE];
  int size = 0;
  void swap(int *a, int *b){
    int aux = *a;
    *a = *b;
    *b = aux;
  }
  void heapify(int i){
    int parent = i;
    int l = 2 * i + 1;
    int r = 2 * i + 2;
    if(l < size && heap[l] < heap[parent])
      parent = l;
    if(r < size && heap[r] < heap[parent])
      parent = r;
    if(parent != i){
      swap(&heap[parent], &heap[i]);
      heapify(parent);
    }
  }
public:
  void insert(int newNode){
      size++;
      heap[size-1] = newNode;
      for(int i = size/2-1; i>=0; i--)
        heapify(i);
  }
  void deleteNode(int node){
    int i;
    for(i = 0; i<size; i++)
      if(heap[i] == node) break;
    swap(&heap[i], &heap[size-1]);
    heap[size-1] = 0;
    size--;
    for(int i = size/2-1; i>=0; i--)
      heapify(i);
  }
  void printArray(){
    for(int i = 0; i<size; i++)
      cout << heap[i] << " ";
    fout << "\n";
  }
  void printMin(){
   fout << heap[0] << "\n";
  }
};

int main(){
  MinHeap minheap;
  int opmem[MAXSIZE];
  int index = 0;
  int n;
  fin >> n;
  for(int i = 0; i<n; i++){
    int op;
    fin >> op;
    if(op == 1){
      int x;
      fin >> x;
      opmem[++index] = x;
      minheap.insert(x);
    }
    else if(op == 2){
      int x;
      fin >> x;
      minheap.deleteNode(opmem[x]);
    }
    else minheap.printMin();
  }
}