Cod sursa(job #2608945)

Utilizator AlexVulpoiuAlexandru Vulpoiu AlexVulpoiu Data 1 mai 2020 22:02:22
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.6 kb
#include <fstream>
#include <algorithm>

using namespace std;

ifstream f("heapuri.in");
ofstream g("heapuri.out");

int n, m, op, x, ins, h[200005], v[200005], poz[200005];
/// h[i] = elementul de pe pozitia i in heap
/// poz[i] = j <=> h[j] este al i-lea element introdus in heap
/// v[i] = j, unde poz[j] = h[i] <=> h[i] este al j-lea element introdus in heap

void push_up(int p)
{
    while(h[p] < h[(p - 1) / 2])
    {
        swap(h[p], h[(p - 1) / 2]);
        swap(poz[v[p]], poz[v[(p - 1) / 2]]);
        swap(v[p], v[(p - 1) / 2]);
        p = (p - 1) / 2;
    }
}

void push_down(int p)
{
    int q;

    while(p * 2 < m - 1 && h[p] > min(h[p * 2 + 1], h[p * 2 + 2]))
    {
        if(h[p * 2 + 1] < h[p * 2 + 2] || p * 2 + 2 >= m)
            q = p * 2 + 1;
        else
            q = p * 2 + 2;
        swap(h[p], h[q]);
        swap(poz[v[p]], poz[v[q]]);
        swap(v[p], v[q]);
        p = q;
    }
}

void insereaza(int x)
{
    poz[++ins] = m;
    v[m] = ins;
    h[m++] = x;
    push_up(m - 1);
}

void sterge(int p)
{
    int q;

    q = poz[p];
    swap(h[q], h[m - 1]);
    swap(poz[v[q]], poz[v[m - 1]]);
    swap(v[q], v[m - 1]);
    m--;
    push_up(q);
    push_down(q);
}

int main()
{
    f >> n;
    m = ins = 0;
    while(n)
    {
        f >> op;
        if(op <= 2)
            f >> x;

        if(op == 1)
            insereaza(x);
        else
            if(op == 2)
                sterge(x);
            else
                g << h[0] << '\n';

        n--;
    }

    f.close();
    g.close();

    return 0;
}