Cod sursa(job #2304578)

Utilizator Mihai145Oprea Mihai Adrian Mihai145 Data 18 decembrie 2018 10:53:54
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.78 kb
#include <fstream>
#include <vector>

using namespace std;

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

struct Heap
{
    int value, id;

    bool operator < (const Heap other)
    {
        return this->value < other.value;
    }
};

vector <Heap> h;
vector <bool> erased;

void PopHead()
{
    swap(h[0], h.back());
    h.pop_back();

    int p = 0;
    while(p < h.size())
    {
        int son = p;

        if(2 * p + 1 < h.size() && h[2 * p + 1] < h[son])
            son = 2 * p + 1;

        if(2 * p + 2 < h.size() && h[2 * p + 2] < h[son])
            son = 2 * p + 2;

        if(son == p)
            break;

        swap(h[p], h[son]);
        p = son;
    }
}

void InsertHeap(int vvalue, int iid)
{
    Heap k; k.value = vvalue; k.id = iid;
    h.push_back(k);

    int p = h.size() - 1;

    while(p)
    {
        if(h[p] < h[(p - 1) / 2])
        {
            swap(h[p], h[(p - 1) / 2]);
            p = (p - 1) / 2;
        }
        else
            break;
    }
}

void Query()
{
    while(!h.empty() && erased[h[0].id])
        PopHead();

    fout << h[0].value << '\n';
}

void Insert(int val)
{
    while(!h.empty() && erased[h[0].id])
        PopHead();

    InsertHeap(val, erased.size());
    erased.push_back(false);
}

void Erase(int x)
{
    erased[x] = true;

    while(!h.empty() && erased[h[0].id])
        PopHead();
}

int main()
{
    int N, x, y;
    fin >> N;

    for(int i = 1; i <= N; i++)
    {
        fin >> x;

        if(x == 3)
            Query();
        else if(x == 1)
        {
            fin >> y;
            Insert(y);
        }
        else
        {
            fin >> y;
            Erase(y - 1);
        }
    }

    return 0;
}