Cod sursa(job #2895124)

Utilizator DafinaTrufasTrufas Dafina DafinaTrufas Data 28 aprilie 2022 19:11:33
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.25 kb
#include <iostream>
#include <fstream>

using namespace std;

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

void inserare(int x)
{
    while(x / 2 && v[h[x]] < v[h[x / 2]])
    {
       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 ok = 0, aux,y = 0;
    while(!ok)
    {
        ok = 1;
        y = x;
        if(v[h[x]] > v[h[2 * y]] && 2 * y <= k) x = 2 * y;
        if(v[h[x]] > v[h[2 * y + 1]] && 2 * y + 1 <= k) x = 2 * y + 1;
        if(x != y) ok = 0;
        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;
        nr++;
        k++;
        v[nr] = x;
        h[k] = nr;
        p[nr] = k;
        inserare(k);
    }
    else if(c == 2)
    {
        f >> x;
        v[x] = -1;
        inserare(p[x]);
        p[h[1]] = 0;
        h[1] = h[k];
        k--;
        p[h[1]] = 1;
        stergere(1);
    }
    else g << v[h[1]] << '\n';
}

return 0;
}