Cod sursa(job #3127904)

Utilizator CiobanuPaulCiobanu Ioan-Paul CiobanuPaul Data 7 mai 2023 22:36:05
Problema Heapuri Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.07 kb
#include <fstream>
#include <iostream>
#include <vector>
using namespace std;

class Heap{
    vector<pair<int, int>> heap;
    vector<int> nums;
public:
    void insert(int x){
        heap.emplace_back(x, nums.size());
        int p = heap.size()-1;
        while((p-1)/2 >= 0 && heap[(p-1/2)].first > heap[p].first){
            auto aux = heap[(p-1/2)];
            heap[(p-1)/2] = heap[p];
            heap[p] = aux;
            nums[heap[p].second] = p;     //updating its stored index
            p = (p-1)/2;
        }
        nums.push_back(p);
    }

    void erase(int i){
        int p = nums[i-1];
        heap[p] = heap.back();
        heap.pop_back();
        while(2*p+1 < heap.size()){
            if(2*p+2 < heap.size() && heap[2*p+1].first >= heap[2*p+2].first){
                if(heap[2*p+2].first < heap[p].first){
                    auto aux = heap[2*p+2];
                    heap[2*p+2] = heap[p];
                    heap[p] = aux;
                    nums[heap[p].second] = p;
                    p = 2*p+2;
                }
            }
            else if(heap[2*p+1].first < heap[p].first){
                auto aux = heap[2*p+1];
                heap[2*p+1] = heap[p];
                heap[p] = aux;
                nums[heap[p].second] = p;
                p = 2*p+1;
            }
            else break;
        }
        nums[heap[p].second] = p;
    }

    int getMin(){
        return heap[0].first;
    }
};


int main() {
        ifstream fin("heapuri.in");
        ofstream fout("heapuri.out");
        int n;
        fin>>n;
        Heap h;
        for(int i=0; i<n; i++){
            int op;
            fin>>op;
            switch (op) {
                case 1:
                    int x;
                    fin>>x;
                    h.insert(x);
                    break;
                case 2:
                     int index;
                     fin>>index;
                     h.erase(index);
                     break;
                case 3:
                    fout<<h.getMin()<<"\n";
                    break;
            }
        }
        return 0;
}