Cod sursa(job #3359575)

Utilizator cont_superscoalaSuperScoala cont_superscoala Data 30 iunie 2026 15:33:24
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.71 kb
/*
https://www.infoarena.ro/problema/heapuri
*/
#include <fstream>
#include <vector>

using namespace std;

vector <int> h, val, poz_in_h;

void schimb(int p1, int p2)
{
    swap(h[p1], h[p2]);
    poz_in_h[h[p1]] = p1;
    poz_in_h[h[p2]] = p2;
}

int tata(int poz)
{
    return (poz - 1) / 2;
}

void urca(int poz)
{
    while (poz != 0 && val[h[poz]] < val[h[tata(poz)]])
    {
        schimb(poz, tata(poz));
        poz = tata(poz);
    }
}

void adauga(int p)
{
    h.push_back(p);
    poz_in_h.push_back((int)h.size());
    urca((int)h.size() - 1);
}

void coboara(int poz)
{
    int fs = 2 * poz + 1, fd = 2 * poz + 2, poz_s = poz;
    if (fs < (int)h.size() && val[h[fs]] < val[h[poz_s]])
    {
        poz_s = fs;
    }
    if (fd < (int)h.size() && val[h[fd]] < val[h[poz_s]])
    {
        poz_s = fd;
    }
    if (poz_s != poz)
    {
        schimb(poz_s, poz);
        coboara(poz_s);
    }
}

void sterge(int poz)
{
    if (poz != (int)h.size() - 1)
    {
        schimb(poz, (int)h.size() - 1);
    }
    h.pop_back();
    urca(poz);
    coboara(poz);
}

int main()
{
    ifstream in("heapuri.in");
    ofstream out("heapuri.out");
    int n;
    in >> n;
    for (int i = 0; i < n; i++)
    {
        int tip;
        in >> tip;
        if (tip == 1)
        {
            int x;
            in >> x;
            val.push_back(x);
            adauga((int)val.size() - 1);
        }
        else if (tip == 2)
        {
            int p;
            in >> p;
            sterge(poz_in_h[p - 1]);
        }
        else
        {
            out << val[h[0]] << "\n";
        }
    }
    in.close();
    out.close();
    return 0;
}