Cod sursa(job #3236842)

Utilizator RosheRadutu Robert Roshe Data 2 iulie 2024 22:38:10
Problema Heapuri Scor 30
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.54 kb
#include <iostream>
#include <vector>
#include <fstream>

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

class MinHeap{
private:
  vector<int> heap;
  void swap(int *a, int *b){
    int aux = *a;
    *a = *b;
    *b = aux;
  }
  void heapify(int i){
    int size = heap.size();
    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){
    int size = heap.size();
    if(size == 0) heap.push_back(newNode);
    else{
      heap.push_back(newNode);
      for(int i = size/2-1; i>=0; i--)
        heapify(i);
    }
  }
  void deleteNode(int node){
    int size = heap.size();
    int i;
    for(i = 0; i<size; i++)
      if(heap[i] == node) break;
    swap(&heap[i], &heap[size-1]);
    heap.pop_back();
    for(int i = size/2-1; i>=0; i--)
      heapify(i);
  }
  void printArray(){
    for(int i = 0; i<heap.size(); i++)
      cout << heap[i] << " ";
    fout << "\n";
  }
  void printMin(){
   fout << heap[0] << "\n";
  }
};

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