Cod sursa(job #2379771)

Utilizator dan.ghitaDan Ghita dan.ghita Data 14 martie 2019 00:38:40
Problema Heapuri Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.9 kb
#include <bits/stdc++.h>
#include <unordered_map>

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

int q, op, x;
vector<int> heap, v;
unordered_map<int, int> removedCnt;

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

void down(int startIndex)
{
    for (int index = startIndex, childIndex = index << 1; childIndex < heap.size();)
    {
        if (heap[index] > heap[childIndex])
            swap(heap[index], heap[childIndex]);
        else
            if (childIndex + 1 < heap.size())
            {
                ++childIndex; // move to right child
                if (heap[index] > heap[childIndex])
                    swap(heap[index], heap[childIndex]);
            }
            else
                return;

        index = childIndex;
        childIndex = index << 1;
    }
}

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

int getMin()
{
    while (removedCnt.find(heap[1]) != removedCnt.end() && removedCnt[heap[1]] > 0)
    {
        --removedCnt[heap[1]];
        swap(heap[1], heap[heap.size() - 1]);
        heap.pop_back();
        down(1);
    }

    return heap[1];
}

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

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