Cod sursa(job #1505736)

Utilizator serban_ioan97Ciofu Serban serban_ioan97 Data 19 octombrie 2015 18:29:46
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.31 kb
#include <cstdio>
#include <algorithm>

#define nmax 200200

using namespace std;

int heap[nmax], a[nmax], pos[nmax];
int i, x, type, l, nr, n;

void push(int x)
{
    while(x/2 && a[heap[x]]<a[heap[x/2]])
    {
        swap(heap[x], heap[x/2]);

        pos[heap[x]]=x;
        pos[heap[x/2]]=x/2;
        x/=2;
    }
}

void pop(int x)
{
    int y=0;

    while(x!=y)
    {
        y=x;
        if(2*y<=l && a[heap[x]]>a[heap[2*y]]) x=2*y;
        if(2*y+1<=l && a[heap[x]]>a[heap[2*y+1]]) x=2*y+1;

        swap(heap[x], heap[y]);

        pos[heap[x]]=x;
        pos[heap[y]]=y;
    }
}

int main()
{
    freopen("heapuri.in", "rt", stdin);
    freopen("heapuri.out", "wt", stdout);

    scanf("%d", &n);

    for(i=1; i<=n; ++i)
    {
        scanf("%d", &type);

        if(type==1)
        {
            scanf("%d", &x);

            ++l, ++nr;

            a[nr]=x;
            heap[l]=nr;
            pos[nr]=l;

            push(l);
        }

        if(type==2)
        {
            scanf("%d", &x);

            a[x]=-1;

            push(pos[x]);

            pos[heap[1]]=0;
            heap[1]=heap[l--];
            pos[heap[1]]=1;

            if(l>1) pop(1);
        }

        if(type==3) printf("%d\n", a[heap[1]]);
    }

    return 0;
}