Cod sursa(job #2776017)

Utilizator caesar2001Stoica Alexandru caesar2001 Data 18 septembrie 2021 14:00:09
Problema Heapuri Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.11 kb
#include <bits/stdc++.h>
#define ll long long
#define lsb(x) x & -x

using namespace std;

class Heap {
private:
    int size = 0, n = 0;
    vector<int> heap = {-1};
    vector<int> posToNode = {-1};
    vector<int> nodeToPos = {-1};
public:
    void swapNodes(int x, int y) {
        swap(heap[x], heap[y]);
        swap(posToNode[nodeToPos[x]], posToNode[nodeToPos[y]]);
        swap(nodeToPos[x], nodeToPos[y]);
    }

    void goUp(int node) {
        if(node == 1)
            return;
        if(heap[node] < heap[node / 2]) {
            swapNodes(node, node / 2);
            goUp(node / 2);
        }
    }

    void add(int x) {
        size ++;
        heap.push_back(x);
        posToNode.push_back(size);
        nodeToPos.push_back(++ n);
        goUp(size);
    }

    void goDown(int node) {
        int dest = -1;
        if(node * 2 <= size && heap[node] > heap[node * 2])
            dest = node * 2;
        if(node * 2 + 1 <= size && heap[node] > heap[node * 2 + 1])
            dest = node * 2 + 1;
        if(dest != -1) {
            swapNodes(dest, node);
            goDown(dest);
        }
    }

    void remove(int pos) {
        int tmp = posToNode[pos];
        swapNodes(size, posToNode[pos]);
        size --;
        heap.pop_back();
        nodeToPos.pop_back();

        if(tmp <= size) {
            goUp(tmp);
            goDown(tmp);
        }
    }

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

    void print() {
        for(auto it : heap)
            cout << it << " ";
        cout << endl;
        for(auto it : posToNode)
            cout << it << " ";
        cout << endl << endl;
    }

};

int main() {
    ifstream cin("heapuri.in");
    ofstream cout("heapuri.out");

    int ntests;
    cin >> ntests;

    Heap myHeap;
    while(ntests --) {
        int type;
        cin >> type;
        if(type == 1) {
            int x;
            cin >> x;
            myHeap.add(x);
        } else if(type == 2) {
            int x;
            cin >> x;
            myHeap.remove(x);
        } else {
            cout << myHeap.getMin() << "\n";
        }
        //myHeap.print();
    }

    return 0;
}