Cod sursa(job #3183035)

Utilizator BuzdiBuzdugan Rares Andrei Buzdi Data 10 decembrie 2023 15:05:15
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.5 kb
#include <fstream>
#include <vector>
#include <unordered_map>

using namespace std;

ifstream cin("heapuri.in");
ofstream cout("heapuri.out");

const int NMAX = 2e5;

int n, indA, indH;
int a[NMAX + 1], heap[NMAX + 1];
unordered_map<int, int> pos;

void Swap(int i, int j)
{
    pos[heap[i]] = j;
    pos[heap[j]] = i;
    swap(heap[i], heap[j]);
}

void HeapifyUp(int i)
{
    while(i >= 1 && heap[i] < heap[i / 2])
    {
        Swap(i, i / 2);
        i /= 2;
    }
}

void HeapifyDown(int i)
{
    int left = 2 * i;
    int right = 2 * i + 1;

    int minPos = i;
    if(left <= indH && heap[left] < heap[minPos])
        minPos = left;
    if(right <= indH && heap[right] < heap[minPos])
        minPos = right;

    if(minPos != i)
    {
        Swap(minPos, i);
        HeapifyDown(minPos);
    }
}

int main()
{
    cin >> n;
    for(int i = 1; i <= n; i++)
    {
        int type;
        cin >> type;

        if(type == 1)
        {
            int x;
            cin >> x;

            a[++indA] = x;
            heap[++indH] = x;
            pos[x] = indH;
            HeapifyUp(indH);
        }
        else if(type == 2)
        {
            int when;
            cin >> when;

            int x = a[when];
            int posX = pos[x];

            Swap(posX, indH);
            indH--;

            HeapifyDown(posX);
            HeapifyUp(posX);
        }
        else
            cout << heap[1] << '\n';
    }


    return 0;
}