Cod sursa(job #2788546)

Utilizator qubitrubbitQubit Rubbit qubitrubbit Data 25 octombrie 2021 21:42:06
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.28 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 = 200013;

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

class Heap
{

private:
    int val[CAPACITY];
    int kth[CAPACITY];
    int nextIdx = 1;
    int count = 0;
    map<int, int> kthIndex;

    void swapNodes(int idx0, int idx1)
    {
        swap(kthIndex[kth[idx0]], kthIndex[kth[idx1]]);
        swap(kth[idx0], kth[idx1]);
        swap(val[idx0], val[idx1]);
    }

    void heapUp(int idx)
    {
        if (idx == 1)
        {
            return;
        }
        if (val[idx] < val[idx / 2])
        {
            swapNodes(idx, idx / 2);
            heapUp(idx / 2);
        }
    }

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

    void deleteByIdx(int idx)
    {
        swapNodes(idx, nextIdx - 1);
        --nextIdx;
        heapDown(idx);
    }

public:
    void addVal(int newVal)
    {
        int idx = nextIdx;
        val[idx] = newVal;
        kth[idx] = ++count;
        kthIndex[count] = idx;
        ++nextIdx;
        heapUp(idx);
    }

    int top()
    {
        return val[1];
    }

    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;
}