Cod sursa(job #2379782)

Utilizator dan.ghitaDan Ghita dan.ghita Data 14 martie 2019 01:02:53
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.74 kb
#include <bits/stdc++.h>
#include <unordered_set>

using namespace std;
 
ifstream f("heapuri.in");
ofstream g("heapuri.out");

int q, op, x;
vector<int> heap, v;
unordered_set<int> removedIndexes;

void up(int startIndex)
{
    for (int index = startIndex, parentIndex = index >> 1; parentIndex > 0; index >>= 1, parentIndex >>= 1)
        if (v[heap[index]] < v[heap[parentIndex]])
            swap(heap[index], heap[parentIndex]);
        else
            return;
}

void down(int startIndex)
{
    for (int index = startIndex, childIndex = index << 1; childIndex < heap.size(); index = childIndex, childIndex <<= 1)
    {
        // choose min child
        if (childIndex + 1 < heap.size() && v[heap[childIndex]] > v[heap[childIndex + 1]])
            ++childIndex;

        if (v[heap[index]] > v[heap[childIndex]])
            swap(heap[index], heap[childIndex]);
        else
            return;
    }
}

void insert(int index)
{
    heap.push_back(index);
    up(heap.size() - 1);
}

int getMin()
{
    while (removedIndexes.find(heap[1]) != removedIndexes.end())
        swap(heap[1], heap[heap.size() - 1]),
        heap.pop_back(),
        down(1);

    return v[heap[1]];
}

int main()
{
    // index from 1
    heap.push_back(0);
    v.push_back(0);

    f >> q;
    int index = 0;
    while (q--)
    {
        f >> op;
        switch (op)
        {
            case 1:
                f >> x;
                v.push_back(x);
                insert(++index);
                break;
            case 2:
                f >> x;
                removedIndexes.insert(x);
                break;
            case 3:
                g << getMin() << '\n';
        }
    }
    
    return 0;
}