Cod sursa(job #1097541)

Utilizator kiralalaChitoraga Dumitru kiralala Data 3 februarie 2014 16:10:01
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.42 kb
#include <fstream>
#define NMAX 200005

using namespace std;

FILE* f=freopen("heapuri.in","r",stdin);
FILE* o=freopen("heapuri.out","w",stdout);

int n;
int heap[NMAX],l;
int hp[NMAX];
int poe[NMAX];

void Swap(int a, int b)
{
    swap(heap[a],heap[b]);
    swap(poe[a],poe[b]);
    swap(hp[poe[a]],hp[poe[b]]);
}

void Shift(int p)
{
    int c=p*2;
    while(c<=l)
    {
        if(c<l&&heap[c]>heap[c+1]) c+=1;
        if(heap[p]>heap[c])
        {
            Swap(p,c);
            p=c;
            c=p*2;
        }
        else break;
    }
}

void Push(int c)
{
    int p=c/2;
    while(p)
    {
        if(heap[p]>heap[c])
        {
            Swap(p,c);
            c=p;
            p=c/2;
        }
        else break;
    }
}

void Insert(int elem, int pos)
{
    heap[++l]=elem;
    hp[pos]=l;
    poe[l]=pos;
    Push(l);
}

void Remove(int pos)
{
    Swap(hp[pos],l);
    l-=1;
    Shift(hp[pos]);
}

int main()
{
    int k,x;

    scanf("%d",&n);

    for(int i=1;i<=n;++i)
    {
        scanf("%d",&k);
        switch(k)
        {
            case 1:
                scanf("%d",&x);
                Insert(x,i);
            break;

            case 2:
                scanf("%d",&x);
                Remove(x);
            break;

            case 3:
                printf("%d\n",heap[1]);
            break;
        }
    }

    return 0;
}