Cod sursa(job #2952916)

Utilizator iProgramInCppiProgramInCpp iProgramInCpp Data 10 decembrie 2022 11:02:31
Problema Heapuri Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.77 kb
#include <bits/stdc++.h>
using namespace std;
//MINHEAP
constexpr int NMAX = 200002;
ifstream fin ("heapuri.in");
ofstream fout("heapuri.out");
typedef pair<int, int> ELEMENT;
ELEMENT H[NMAX]; // .first = the number, .second = the input position
int posInHeap[NMAX];
int n;

void insert_element(int i)
{
    n++;
    H[n] = { i, n };
    posInHeap[n] = n;
}

int get_min()
{
    return H[1].first;
}

// finalize the heap
void combine(int i)
{
    ELEMENT x = H[i];
    int parent = i, child = 2 * i;

    while (child <= n)
    {
        // check if the right child is the minimal one instead
        if (child + 1 <= n && H[child + 1] < H[child])
            child++;

        if (H[child] < x)
        {
            posInHeap[H[child].second] = parent;
            H[parent] = H[child];
            parent = child;
            child  = 2 * parent;
        }
        else break;
    }

    posInHeap[x.second] = parent;
    H[parent] = x;
}

void finalize()
{
    for (int i = n / 2; i > 0; i--)
    {
        combine(i);
    }
}

void erase_element(int elem)
{
    // swap the last element with this one
    posInHeap[H[n].second] = elem;
    posInHeap[H[elem].second] = -1;
    swap(H[n], H[elem]);
    n--;

    combine(elem);
}

int main()
{
    int nops;
    fin >> nops;

    while (nops)
    {
        nops--;

        int op, parm;
        fin >> op;
        if (op != 3) fin >> parm;

        if (op == 1)
        {
            insert_element(parm);
        }
        else if (op == 2)
        {
            finalize();
            erase_element(posInHeap[parm]);
        }
        else if (op == 3)
        {
            finalize();
            fout << get_min() << '\n';
        }
    }

    return 0;
}