Cod sursa(job #3130130)

Utilizator PatrunjelxdVarona Antoniu Patrunjelxd Data 16 mai 2023 21:52:58
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.69 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

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

class Heap {
private:
    vector<int> heap;
    int size;

public:
    Heap() {
        heap.push_back(-1);
        size = 0;
    }

    int getMin() {
        return heap[1];
    }

    void add(int val) {
        heap.push_back(val);
        size++;
        int i = size;
        while (i > 1 && heap[i/2] > heap[i]) {
            swap(heap[i/2], heap[i]);
            i = i/2;
        }
    }

    void pop(int val) {
        int index = 0;
        for(int i=1;i<=size;i++)
        {
            if(heap[i] == val){index = i; break;}
        }
        swap(heap[index], heap[size]);
        heap.pop_back();
        size--;
        int i = index;
        while (i > 1 && heap[i/2] > heap[i]) {
            swap(heap[i/2], heap[i]);
            i = i/2;
        }
        while (2*i <= size) {
            int j = 2*i;
            if (j < size && heap[j] > heap[j+1]) j++;
            if (heap[i] <= heap[j]) break;
            swap(heap[i], heap[j]);
            i = j;
        }
    }
};

int main() {
    Heap heap;
    vector<int> pozitie;
    int n;
    fin>>n;
    for(int i=0;i<n;i++)
    {
        int optiune;
        fin>>optiune;
        if(optiune == 1)
        {
            int x;
            fin>>x;
            heap.add(x);
            pozitie.push_back(x);
        }
        else if(optiune == 2)
        {
            int x;
            fin>>x;
            int index = 0;
            while(index != x - 1) index++;
            heap.pop(pozitie[index]);
        }
        else if(optiune == 3)
        {
            fout<<heap.getMin()<<endl;
        }
    }
    return 0;
}