Cod sursa(job #3129290)

Utilizator willOcanaru Mihai will Data 13 mai 2023 20:29:21
Problema Heapuri Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.05 kb
#include <iostream>
#include <vector>
#include <algorithm>
#include <fstream>
#include <limits>

using namespace std;

vector<int> heap;

void sift_up(int x) {
    heap.push_back(x);
    int i = heap.size() - 1;
    while (i > 0 && heap[i] < heap[(i - 1) / 2]) {
        swap(heap[i], heap[(i - 1) / 2]);
        i = (i - 1) / 2;
    }
}

void sift_down() {
    int x = heap[0];
    heap[0] = heap.back();
    heap.pop_back();
    int i = 0;
    while (2 * i + 1 < heap.size()) {
        int left_child = 2 * i + 1;
        int right_child = 2 * i + 2;
        int min_child = left_child;
        if (right_child < heap.size() && heap[right_child] < heap[left_child]) {
            min_child = right_child;
        }
        if (heap[i] > heap[min_child]) {
            swap(heap[i], heap[min_child]);
            i = min_child;
        } else {
            break;
        }
    }
}

int get_min() {
    return heap[0];
}

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

    int n;
    fin >> n;

    for (int i = 0; i < n; i++) {
        int op;
        fin >> op;
        if (op == 1) {
            int x;
            fin >> x;
            sift_up(x);
        } else if (op == 2) {
            int x;
            fin >> x;
            auto it = find(heap.begin(), heap.end(), x);
            if (it != heap.end()) {
                int index = it - heap.begin();
                swap(heap[index], heap.back());
                heap.pop_back();
                if (index < heap.size()) {
                    if (heap[index] < heap[(index - 1) / 2]) {
                        sift_up(heap[index]);
                    } else {
                        sift_down();
                    }
                }
            }
        } else if (op == 3) {
            if (!heap.empty()) {
                fout << get_min() << endl;
            } else {
                fout << "Heap is empty!" << endl;
            }
        }
    }

    fin.close();
    fout.close();

    return 0;
}