Cod sursa(job #3277002)

Utilizator not_anduAndu Scheusan not_andu Data 15 februarie 2025 11:12:14
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.98 kb
#include <bits/stdc++.h>
#include <unordered_map>

using namespace std;

#define INFILE "heapuri.in"
#define OUTFILE "heapuri.out"

class MinHeap {
private:
    vector<int> v;

    void heapify_up(int idx) {
        while (idx > 0 && v[idx] < v[(idx - 1) / 2]) {
            swap(v[idx], v[(idx - 1) / 2]);
            idx = (idx - 1) / 2;
        }
    }

    void heapify_down(int idx) {
        while (2 * idx + 1 < v.size()) {
            int left = 2 * idx + 1;
            int right = 2 * idx + 2;
            int smallest = left;
            if (right < v.size() && v[right] < v[left])
                smallest = right;
            if (v[idx] <= v[smallest])
                break;
            swap(v[idx], v[smallest]);
            idx = smallest;
        }
    }

public:
    MinHeap() {}

    int top() {
        if (!v.empty()) return v.front();
        return -1;
    }

    void insert(int number) {
        v.push_back(number);
        heapify_up(v.size() - 1);
    }

    void erase(int number) {
        auto it = find(v.begin(), v.end(), number);
        if (it != v.end()) {
            int idx = it - v.begin();
            swap(v[idx], v.back());
            v.pop_back();
            heapify_down(idx);
        }
    }
};

void solve(){

    MinHeap v;
    int queries; cin >> queries;

    int cnt = 1;
    unordered_map<int, int> fr;

    for(int i = 1; i <= queries; ++i){
        int type; cin >> type;
        if(type == 1){
            int number; cin >> number;
            v.insert(number);
            fr[cnt] = number;
            ++cnt;
        }
        else if(type == 2){
            int index; cin >> index;
            v.erase(fr[index]);
        }
        else {
            cout << v.top() << '\n';
        }
    }

}

int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(0), cout.tie(0);
    freopen(INFILE, "r", stdin);
    freopen(OUTFILE, "w", stdout);
    solve();
    return 0;
}