Cod sursa(job #3252828)

Utilizator adelinapetreAdelina Petre adelinapetre Data 31 octombrie 2024 12:07:20
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.42 kb
#include <fstream>
using namespace std;

ifstream cin ("heapuri.in");
ofstream cout ("heapuri.out");

const int Nmax = 2e5 + 5;

struct hp
{
    int val, ord;
}heap[Nmax];

int poz[Nmax];

int sz = 0;

void myswap(int p, int t)
{
    swap(heap[p], heap[t]);
    swap(poz[heap[p].ord], poz[heap[t].ord]);
}

void up(int p)
{
    while(p > 1 && heap[p].val < heap[p / 2].val)
    {
        myswap(p, p / 2);
        p /= 2;
    }
}

void down(int p)
{
    while(p * 2 <= sz)
    {
        int t = p * 2;
        if(p * 2 < sz && heap[t + 1].val < heap[t].val)
            t ++;
        if(heap[p].val > heap[t].val)
            myswap(p, t), p = t;
        else
            break;

    }
}

void add(int val, int ord)
{
    heap[++sz] = {val, ord};
    poz[ord] = sz;
    up(sz);
}

void sterg(int ord)
{
    if(poz[ord] == sz)
        sz --;
    else
    {
        int aux = poz[ord];
        myswap(poz[ord], sz);
        sz --;
        up(aux);
        down(aux);
    }
}

int main()
{
    int n, tip, x, i, ordi = 0;
    cin >> n;
    for(i = 1; i <= n; i ++)
    {
        cin >> tip;
        if(tip == 1)
        {
            cin >> x;
            ordi ++;
            add(x, ordi);
        }
        else if (tip == 2)
        {
            cin >> x;
            sterg(x);
        }
        else
            cout << heap[1].val << '\n';
    }
    return 0;
}