Cod sursa(job #2872684)

Utilizator acostin643costin andrei acostin643 Data 17 martie 2022 17:50:50
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.42 kb
#include <fstream>
#include <algorithm>

using namespace std;
const int NMAX = 200000;

ifstream fin("heapuri.in");
ofstream fout("heapuri.out");

int heap[4 * NMAX + 5], poz[NMAX + 5];
int v[NMAX + 5], n, p, k, st, dr, best;

void mySwap(int a, int b)
{
    swap(poz[heap[a]], poz[heap[b]]);
    swap(heap[a], heap[b]);
}

void adaug(int x)
{
    v[++n] = x;
    heap[++k] = n;
    poz[n] = k;

    p = k;

    while(p > 1 && v[heap[p]] < v[heap[p / 2]])
    {
        mySwap(p, p / 2);
        p /= 2;
    }
}

void elimin(int x)
{
    p = poz[x];
    mySwap(p, k);
    k--;

    while(p > 1 && v[heap[p]] < v[heap[p] / 2])
    {
        mySwap(p, p / 2);
        p /= 2;
    }

    while(p * 2 <= k)
    {
        st = p * 2;
        dr = st + 1;
        best = st;
        if(dr <= k && v[heap[st]] > v[heap[dr]])
            best = dr;
        if(v[heap[p]] > v[heap[best]])
            mySwap(p, best);
        else
            break;
        p = best;
    }
}

int main()
{
    int m, test, x;
    fin >> m;
    for(int i = 1; i <= m; i++)
    {
        fin >> test;
        if(test == 1)
        {
            fin >> x;
            adaug(x);
        }
        else if(test == 2)
        {
            fin >> x;
            elimin(x);
        }
        else
            fout << v[heap[1]] << '\n';
    }

    fin.close();
    fout.close();

    return 0;
}