Cod sursa(job #3233402)

Utilizator sireanu_vladSireanu Vlad sireanu_vlad Data 3 iunie 2024 11:41:48
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.14 kb
#include <iostream>
#include <vector>
using namespace std;

class MinHeap {
public:
    vector<int> v;
    vector<int> h;
    vector<int> pos;

    int parent(int i) {
        return (i - 1) / 2;
    }
    void push(int elem) {
        v.push_back(elem);
        h.push_back(v.size() - 1);
        pos.push_back(h.size() - 1);

        fix_heap(h.size() - 1);
    }
    void fix_heap(int i) {
        while (i > 0 && v[h[i]] < v[h[parent(i)]]) {
            swap(pos[h[i]], pos[h[parent(i)]]);
            swap(h[i], h[parent(i)]);
            i = parent(i);
        }
    }
    int top() {
        return v[h[0]];
    }
    int left(int i) {
        return (i + 1) * 2 - 1;
    }
    int right(int i) {
        return (i + 1) * 2;
    }
    void pop() {
        swap(pos[h[0]], pos[h[h.size() - 1]]);
        swap(h[0], h[h.size() - 1]);

        h.pop_back();
        
        heapify(0);
    }
    void heapify(int index) {
        while (true) {
            int l = left(index);
            int r = right(index);
            int maxx = index;

            if (l < h.size() && v[h[l]] < v[h[maxx]]) {
                maxx = l;
            }
            if (r < h.size() && v[h[r]] < v[h[maxx]]) {
                maxx = r;
            }
            if (maxx == index) {
                break;
            }
            swap(pos[h[index]], pos[h[maxx]]);
            swap(h[index], h[maxx]);
            index = maxx;
        }
    }
    void remove(int index) {
        v[index] = -1;
        fix_heap(pos[index]);
        pop();
    }
};

int main() {
    freopen("heapuri.in", "r", stdin);
    freopen("heapuri.out", "w", stdout);

    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);

    MinHeap heap;

    int n;
    cin >> n;

    while (n--) {
        int t;
        cin >> t;

        if (t == 1 || t == 2) {
            int x;
            cin >> x;
            if (t == 1) {
                heap.push(x);
            } else if (t == 2) {
                heap.remove(x - 1);
            }
        } else if (t == 3) {
            cout << heap.top() << '\n';
        }
    }
}