Cod sursa(job #3123279)

Utilizator radustn92Radu Stancu radustn92 Data 22 aprilie 2023 20:04:46
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.87 kb
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
using namespace std;

int N;

struct Node {
    int key, val;

    Node(int key, int val) : key(key), val(val) {
    }

    bool operator < (const Node& other) const {
        return val < other.val;
    }
};
vector<Node> heap;
vector<int> keyToNode;

void swapIndices(int idx1, int idx2) {
    keyToNode[heap[idx1].key] = idx2;
    keyToNode[heap[idx2].key] = idx1;
    swap(heap[idx1], heap[idx2]);
}

void goUp(int idx) {
    while (idx && heap[idx] < heap[idx / 2]) {
        swapIndices(idx, idx / 2);
        idx /= 2;
    }
}

void insertHeap(int key, int val) {
    heap.push_back({key, val});
    keyToNode.resize(key + 1);
    keyToNode[key] = heap.size() - 1;

    goUp(heap.size() - 1);
}

void goDown(int idx) {
    while (idx * 2 < heap.size()) {
        int bestChild = idx * 2;
        if (idx * 2 + 1 < heap.size() && heap[idx * 2 + 1] < heap[idx * 2]) {
            bestChild = idx * 2 + 1;
        }
        if (heap[bestChild] < heap[idx]) {
            swapIndices(idx, bestChild);
            idx = bestChild;
        } else {
            break;
        }
    }
}

void deleteIdx(int idx) {
    swapIndices(heap.size() - 1, idx);
    keyToNode[heap.back().key] = -1;
    heap.pop_back();

    if (idx > 0 && heap[idx] < heap[idx / 2]) {
        goUp(idx);
    } else {
        goDown(idx);
    }
}

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

    cin >> N;
    int query, insertions = 0, elem;
    for (int idx = 0; idx < N; idx++) {
        cin >> query;
        if (query == 1) {
            cin >> elem;
            insertions++;
            insertHeap(insertions, elem);
        } else if (query == 2) {
            cin >> elem;
            deleteIdx(keyToNode[elem]);
        } else {
            cout << heap[0].val << "\n";
        }
    }
    return 0;
}