Cod sursa(job #3357519)

Utilizator MihneaC828Mihnea Circo MihneaC828 Data 10 iunie 2026 16:24:42
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.62 kb
#include <iostream>
#include <fstream>

using namespace std;
ifstream fin("heapuri.in");
ofstream fout("heapuri.out");
int h[200005];
int crono[200005];
int poz_heap[200005];
int cnt = 0;
int adds = 0;

void schimba(int i, int j) {
    swap(h[i], h[j]);
    swap(crono[i], crono[j]);
    poz_heap[crono[i]] = i;
    poz_heap[crono[j]] = j;
}

void promovare(int k) {
    while(k > 1)
    {
        if(h[k] < h[k / 2])
        {
            schimba(k, k / 2);
            k /= 2;
        }
        else
        {
            return;
        }
    }
}

void cernere(int k, int n)
{
    while(2 * k <= n)
    {
        int copchil = 2 * k;
        if(copchil + 1 <= n && h[copchil + 1] < h[copchil])
            copchil++;
        if(h[k] < h[copchil])
            return;
        else {
            schimba(k, copchil);
            k = copchil;
        }
    }
}

int main() 
{
    int nr, c;
    fin >> nr;
    while(nr--)
    {
        fin >> c;
        if(c == 1)
        {
            int x;
            fin >> x;
            cnt++;
            adds++;
            h[cnt] = x;
            crono[cnt] = adds;
            poz_heap[adds] = cnt;
            promovare(cnt);
        }
        else if(c == 2)
        {
            int x;
            fin >> x;
            int poz = poz_heap[x];
            schimba(poz, cnt);
            cnt--;
            if(poz <= cnt)
            {
                promovare(poz);
                cernere(poz, cnt);
            }
        }
        else if(c == 3)
        {
            fout << h[1] << '\n';
        }
    }
    return 0;
}