Cod sursa(job #2931714)

Utilizator VladTZYVlad Tiganila VladTZY Data 31 octombrie 2022 19:18:26
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.87 kb
#include <fstream>

#define NMAX 200005

using namespace std;

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

int questions, type, val, ind, heapSize;
bool deleted[NMAX];
pair <int, int> heap[NMAX];

void addToHeap(int val, int poz) {

    heapSize++;
    heap[heapSize] = {val, poz};

    int pozNow = heapSize;
    int father = heapSize / 2;

    while(father >= 1 && heap[father].first > heap[pozNow].first) {

        swap(heap[father], heap[pozNow]);
        pozNow = father;
        father = pozNow / 2;
    }
}

void deleteFromHeap() {

    heap[1] = heap[heapSize];
    heapSize--;

    int pozNow = 1;
    int child1 = pozNow * 2;
    int child2 = pozNow * 2 + 1;

    while ( (child1 <= heapSize && heap[pozNow].first > heap[child1].first)
         || (child2 <= heapSize && heap[pozNow].first > heap[child2].first) ) {

        int mini = heap[pozNow].first;
        int miniPoz = pozNow;

        if (child1 <= heapSize && mini > heap[child1].first) {

            mini = heap[child1].first;
            miniPoz = child1;
        }

        if (child2 <= heapSize && mini > heap[child2].first) {

            mini = heap[child2].first;
            miniPoz = child2;
        }

        swap(heap[pozNow], heap[miniPoz]);
        pozNow = miniPoz;
        child1 = pozNow * 2;
        child2 = pozNow * 2 + 1;

    }
}

int main()
{
    f >> questions;

    while (questions--) {
        f >> type;

        if (type == 1) {
            f >> val;

            ind++;
            addToHeap(val, ind);
        }

        if (type == 2) {
            f >> val;

            deleted[val] = true;
        }

        if (type == 3) {

            while (deleted[heap[1].second]) {
                deleteFromHeap();
            }

            g << heap[1].first << "\n";
        }
    }

    return 0;
}