Cod sursa(job #2741906)

Utilizator icnsrNicula Ionut icnsr Data 19 aprilie 2021 18:27:38
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.96 kb
#include <cstdio>
#include <vector>
#include <algorithm>
#include <unordered_set>

using value_t = std::pair<int, unsigned>;

const auto compare = [](const value_t& x1, const value_t& x2)
{
        return x1.first > x2.first;
};

class LazyHeap
{
public:
        LazyHeap() = default;

        void push(const int x)
        {
                elements.push_back({x, count});
                std::push_heap(elements.begin(), elements.end(), compare);
                ++count;
        }

        void erase(const unsigned k)
        {
                deleted[k] = true;
        }

        int top()
        {
                while(deleted[elements.front().second])
                {
                        std::pop_heap(elements.begin(), elements.end(), compare);
                        elements.pop_back();
                }

                return elements.front().first;
        }

        static constexpr unsigned MAX_N = 200000;

private:
        std::vector<value_t> elements;
        std::array<bool, MAX_N + 1> deleted;
        unsigned count = 1;
};

int main()
{
        FILE* fin = fopen("heapuri.in", "r");
        FILE* fout = fopen("heapuri.out", "w");

        unsigned N;
        fscanf(fin, "%u", &N);

        LazyHeap heap;
        for(unsigned i = 0; i < N; ++i)
        {
                int op;
                fscanf(fin, "%d", &op);

                int value;

                if(op != 3)
                {
                        fscanf(fin, "%d", &value);
                }

                switch(op)
                {
                        case 1:
                                heap.push(value);
                                break;
                        case 2:
                                heap.erase(value);
                                break;
                        case 3:
                                fprintf(fout, "%d\n", heap.top());
                                break;
                }
        }

        fclose(fin);
        fclose(fout);
}