Cod sursa(job #2547720)

Utilizator pepsiM4A1Ozturk Arif pepsiM4A1 Data 15 februarie 2020 16:57:23
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.37 kb
#include <cstdio>
#include <algorithm>
using namespace std;
const int nmax = 200004;
int heap[nmax];
int heapN;
int orderOfNum;
int where[nmax],cronological[nmax];
int n;
inline void citire()
{
    scanf("%d",&n);
}
void upcheck(int pos)
{
    while(pos/2!=0&&heap[pos]<heap[pos/2]) //pos/2 == 0 inseamna pos = 1 adica suntem in radacina
    {
        swap(heap[pos],heap[pos/2]);
        swap(where[cronological[pos]],where[cronological[pos/2]]);
        swap(cronological[pos],cronological[pos/2]);
        pos/=2;
    }
}
void downCheck(int pos)
{
    while(1)
    {
        int theCase = 0;
        int minim = heap[pos];
        if(minim>heap[2*pos]&&2*pos<=heapN)
        {
            minim = heap[2*pos];
            theCase = 1;
        }
        if(minim>heap[2*pos+1]&&2*pos+1<=heapN)
        {
            minim = heap[2*pos+1];
            theCase = 2;
        }
        if(theCase == 0) break;
        else
        {
            if(theCase == 1)
            {
                swap(heap[pos],heap[2*pos]);
                swap(where[cronological[pos]],where[cronological[2*pos]]);
                swap(cronological[pos],cronological[2*pos]);
                pos = 2*pos;
            }
            else
            {
                swap(heap[pos],heap[2*pos+1]);
                swap(where[cronological[pos]],where[cronological[2*pos+1]]);
                swap(cronological[pos],cronological[2*pos+1]);
                pos = 2*pos+1;
            }
        }
    }
}
void addToHeap(int val)
{
    heap[++heapN] = val;
    cronological[heapN] = ++orderOfNum;
    where[orderOfNum] = heapN;
    upcheck(heapN);
}
void removeFromHeap(int pos)
{
    pos = where[pos];
    swap(heap[pos],heap[heapN]);
    swap(where[cronological[pos]],where[cronological[heapN]]);
    swap(cronological[pos],cronological[heapN]);
    --heapN;
    downCheck(pos);
    upcheck(pos);

}
inline void solve()
{
    int x,y;
    for(;n>0;--n)
    {
        scanf("%d",&x);
        if(x==1)
        {
            scanf("%d",&y);
            addToHeap(y);
        }
        else if(x==2)
        {
            scanf("%d",&y);
            removeFromHeap(y);
        }
        else if(x==3) printf("%d\n",heap[1]);

    }
}
int main()
{
    freopen ("heapuri.in","r",stdin);
    freopen ("heapuri.out","w",stdout);
    citire();
    solve();
}