Cod sursa(job #3245754)

Utilizator schema_227Stefan Nicola schema_227 Data 30 septembrie 2024 16:18:07
Problema Heapuri Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.92 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <unordered_set>

using namespace std;

ifstream in("heapuri.in");
ofstream out("heapuri.out");

void Ascend(vector<int>& heap, int i) {
    while(i > 0) {
        int tata = (i - 1) / 2;
        if(heap[i] < heap[tata])
            swap(heap[i], heap[tata]), i = tata;
        else
            break;
    }
}

void Descend(vector<int>& heap, int i) {
    while(true) {
        int stanga = 2 * i + 1;
        int dreapta = 2 * i + 2;
        int top = i;

        if(stanga < heap.size() && heap[stanga] < heap[top])
            top = stanga;
        if(dreapta < heap.size() && heap[dreapta] < heap[top])  /
            top = dreapta;
        if(top != i) {
            swap(heap[i], heap[top]);
            i = top;
        } else
            break;
    }
}

void Insert(vector<int>& heap, int val) {
    heap.push_back(val);
    Ascend(heap, heap.size() - 1);
}

int HeapMin(vector<int>& heap, unordered_set<int>& sterse) {
    while(!heap.empty() && sterse.find(heap[0]) != sterse.end()) {
        swap(heap[0], heap.back());
        heap.pop_back();
        if(!heap.empty())
            Descend(heap, 0);
    }
    if(heap.empty())
        return -1;
    return heap[0];
}

int main() {
    int m;
    in >> m;

    vector<int> heap;
    vector<int> order;
    unordered_set<int> sterse;

    for(int i = 0; i < m; i++) {
        int op;
        in >> op;
        if(op == 1) {
            int x;
            in >> x;
            Insert(heap, x);
            order.push_back(x);
        } else if(op == 2) {
            int x;
            in >> x;
            sterse.insert(order[x - 1]);
        } else if(op == 3) {
            int minn = HeapMin(heap, sterse);
            if(minn != -1)
                out << minn << '\n';
            else
                out << "-1";
        }
    }

    return 0;
}