Cod sursa(job #2788539)

Utilizator qubitrubbitQubit Rubbit qubitrubbit Data 25 octombrie 2021 21:09:05
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.5 kb
#include <fstream>
#include <vector>
#include <cmath>
#include <iostream>
#include <map>
using namespace std;

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

const int CAPACITY = 200001;

void swap(int &a, int &b)
{
    int temp = a;
    a = b;
    b = temp;
}

class Heap
{
    class Node
    {
    public:
        int val;
        int kth;

        Node(int val, int kth)
        {
            this->val = val;
            this->kth = kth;
        }
    };

private:
    vector<Node> nodes;
    int count = 0;
    map<int, int> kthIndex;

    void swap(int idx0, int idx1)
    {
        kthIndex[nodes[idx0].kth] = idx1;
        kthIndex[nodes[idx1].kth] = idx0;
        Node temp = nodes[idx0];
        nodes[idx0] = nodes[idx1];
        nodes[idx1] = temp;
    }

    void heapUp(int idx)
    {
        Node curr = nodes[idx];
        Node parent = nodes[idx / 2];
        if (curr.val < parent.val)
        {
            swap(idx, idx / 2);
            heapUp(idx / 2);
        }
    }

    void heapDown(int idx)
    {
        int lowerBound = nodes.size() - 1;
        int left = idx * 2;
        int right = idx * 2 + 1;
        if (left > lowerBound)
        {
            return;
        }
        int minIdx = idx;
        if (nodes[left].val < nodes[minIdx].val)
        {
            minIdx = left;
        }
        if (right <= lowerBound && nodes[right].val < nodes[minIdx].val)
        {
            minIdx = right;
        }
        if (idx != minIdx)
        {
            swap(idx, minIdx);
            heapDown(minIdx);
        }
    }

    void deleteByIdx(int idx)
    {
        swap(idx, nodes.size() - 1);
        nodes.pop_back();
        heapDown(idx);
    }

public:
    void addVal(int val)
    {
        Node node(val, ++count);
        nodes.push_back(node);
        kthIndex[count] = nodes.size() - 1;
        heapUp(nodes.size() - 1);
    }

    int top()
    {
        return nodes[0].val;
    }

    void removeKth(int k)
    {
        deleteByIdx(kthIndex[k]);
    }
};

int main()
{
    int t, val, op, k;
    Heap h;
    fin >> t;
    while (t-- > 0)
    {
        fin >> op;
        if (op == 1)
        {
            fin >> val;
            h.addVal(val);
        }
        else if (op == 2)
        {
            fin >> k;
            h.removeKth(k);
        }
        else if (op == 3)
        {
            fout << h.top() << "\n";
        }
    }
    return 0;
}