Cod sursa(job #2754120)

Utilizator rapidu36Victor Manz rapidu36 Data 25 mai 2021 09:43:16
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.43 kb
#include <fstream>

using namespace std;

const int N = 2e5 + 1;

int h[N], v[N], poz[N], n, nh, nop;

void schimba(int p1, int p2)
{
    ///schimba h[p1] cu h[p2]
    swap(h[p1], h[p2]);
    poz[h[p1]] = p1;
    poz[h[p2]] = p2;
}

void urca(int p)
{
    while (p > 1 && v[h[p]] < v[h[p/2]])
    {
        schimba(p, p/2);
        p /= 2;
    }
}

void adauga(int p)
{
    h[++nh] = p;
    poz[p] = nh;
    urca(nh);
}

void coboara(int p)
{
    int fs = 2*p, fd = 2*p + 1, optim = p;
    if (fs <= nh && v[h[fs]] < v[h[optim]])
    {
        optim = fs;
    }
    if (fd <= nh && v[h[fd]] < v[h[optim]])
    {
        optim = fd;
    }
    if (optim != p)
    {
        schimba(optim, p);
        coboara(optim);
    }
}

void sterge(int p)
{
    if (p == nh)
    {
        nh--;
    }
    else
    {
        schimba(p, nh--);
        urca(p);
        coboara(p);
    }
}

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