Cod sursa(job #2892268)

Utilizator Tudose_StefanTudose Alexandru Stefan Tudose_Stefan Data 21 aprilie 2022 15:12:27
Problema Heapuri Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.82 kb
#include <fstream>
#include <vector>
#include <unordered_set>
#include <iostream>

using namespace std;

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

vector <int> hip, ordine;
unordered_set <int> sterse;
int nrOperatii, nr, sizeHip, operatie;

void urcare(int ptr)
{
    while (hip[ptr] < hip[(ptr-1)/2] && ptr > 0)
    {
        swap(hip[ptr], hip[(ptr-1)/2]);
        ptr = (ptr-1)/2;
    }
}

void coborare(int ptr)
{
    bool fiu;
    while (true)
    {
        if (ptr * 2 + 1 < sizeHip)
        {
            if (hip[ptr*2] < hip[ptr*2+1])
                fiu = 0;
            else
                fiu = 1;
            if (hip[ptr*2+fiu] < hip[ptr])
            {
                swap(hip[ptr*2+fiu], hip[ptr]);
                ptr = ptr*2+fiu;
            }
            else
                return;
        }
        else if (ptr * 2 < sizeHip)
        {
            if (hip[ptr*2] < hip[ptr])
                swap(hip[ptr*2], hip[ptr]);
            return;
        }
        else
            return;
    }


}


int main()
{
    fin >> nrOperatii;
    while (nrOperatii--)
    {
        fin >> operatie;
        if (operatie == 1)
        {
            fin >> nr;
            hip.push_back(nr);
            ordine.push_back(nr);
            urcare(hip.size()-1);
        }
        if (operatie == 2)
        {
            fin >> nr;
            sterse.insert(ordine[nr-1]);
        }
        if (operatie == 3)
        {
            while(sterse.find(hip[0])!= sterse.end())
            {
                sterse.erase(hip[0]);
                hip[0] = hip[hip.size()-1];
                hip.erase(hip.end()-1);
                sizeHip--;
                coborare(0);
            }
            fout << hip[0] << '\n';
        }
    }

    return 0;
}