Cod sursa(job #2895090)

Utilizator DafinaTrufasTrufas Dafina DafinaTrufas Data 28 aprilie 2022 18:52:52
Problema Heapuri Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.29 kb
#include <iostream>
#include <fstream>

using namespace std;

int v[200001], h[200001], p[200001], nr;

void inserare(int x)
{
    int ok = 0, aux;
    while(x / 2 && !ok)
    {
        ok = 1;
        if (v[h[x]] < v[h[x / 2]])
        {
            ok = 0;
            aux = h[x];
            h[x] = h[x / 2];
            h[x / 2] = aux;
            p[h[x]] = x;
            p[h[x / 2]] = x / 2;
            x /= 2;
        }
    }
}

void stergere(int x)
{

    int aux, y = 0;
    while(y != x)
    {
        y = x;
        if(v[h[x]] > v[h[2 * y]] && 2 * y <= nr) x = 2 * y;
        if(v[h[x]] > v[h[2 * y + 1]] && 2 * y + 1 <= nr) x = 2 * y + 1;
        aux = h[x];
        h[x] = h[y];
        h[y] = aux;
        p[h[x]] = x;
        p[h[y]] = y;
    }
}

int main()
{int n, x, c, i, j;
ifstream f("heapuri.in");
ofstream g("heapuri.out");
f >> n;
for(i = 0; i < n; i++)
{
    f >> c;
    if(c == 1)
    {
        f >> x;
        v[++nr] = x;
        h[nr] = p[nr] = nr;
        inserare(nr);
    }
    else if(c == 2)
    {
        f >> x;
        v[x] = -1;
        inserare(p[x]);
        p[h[1]] = 0;
        h[1] = h[nr];
        nr--;
        p[h[1]] = 1;
        stergere(1);
    }
    else g << v[h[1]] << '\n';
}

return 0;
}