Cod sursa(job #2379741)

Utilizator dan.ghitaDan Ghita dan.ghita Data 13 martie 2019 23:04:04
Problema Heapuri Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.81 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> removed;

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

void siftDown(int startIndex)
{
    for(int index = startIndex, leftChildIndex = startIndex << 1; leftChildIndex < heap.size(); leftChildIndex = index << 1)
    {
        if (heap[index] > heap[leftChildIndex])
            swap(heap[index], heap[leftChildIndex]),
            index = leftChildIndex;
        else if (leftChildIndex + 1 < heap.size() && heap[index] > heap[leftChildIndex + 1])
            swap(heap[index], heap[leftChildIndex + 1]),
            index = leftChildIndex + 1;
        else
            break;
    }

}

void insert(int val)
{
    heap.push_back(val);
    siftUp(heap.size() - 1);
}

int getMin()
{
    // lazy deletion
    while (removed.find(heap[1]) != removed.end())
    {
        swap(heap[1], heap[heap.size() - 1]);
        heap.pop_back();
        siftDown(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;
                removed.insert(v[x]);
                break;
            case 3:
                g << getMin() << '\n';
        }
    }
    
    return 0;
}