Cod sursa(job #926700)

Utilizator supermitelArdelean Razvan Mitel supermitel Data 25 martie 2013 12:30:19
Problema Heapuri Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.46 kb
#include <cstdio>
#include <algorithm>

using namespace std;

struct element
{
    int val;
    int ord;
    element(int x=0)
    {
        val=x;
        ord=0;
    }
};

element heap[270000];
int poz[200000];
int np,nh,n;

void push(element x)
{
    element aux;
    heap[++nh]=x;
    poz[x.ord]=nh;
    while(poz[x.ord]/2 && x.val<heap[poz[x.ord]/2].val)
    {
        aux=heap[poz[x.ord]/2];
        heap[poz[x.ord]/2]=x;
        heap[poz[x.ord]]=aux;
        poz[aux.ord]=poz[x.ord];
        poz[x.ord]/=2;
    }
}

void pop(int x)
{
    if(heap[x].ord==0)
        return;
    int aux;
    if(heap[x*2].ord==0)
        aux=x*2+1;
    else if(heap[x*2+1].ord==0)
        aux=x*2;
    else if(heap[x*2].val<heap[x*2+1].val)
        aux=x*2;
    else aux=x*2+1;

    heap[x]=heap[aux];
    poz[heap[aux].ord]/=2;
    pop(aux);
}

int main()
{
    freopen("heapuri.in","r",stdin);
    freopen("heapuri.out","w",stdout);
    scanf("%d",&n);
    int procedure;
    element x;
    for(int i=0;i<n;i++)
    {
        scanf("%d",&procedure);
        switch(procedure)
        {
        case 1:
            x.ord=++np;
            scanf("%d",&x.val);
            push(x);
            break;
        case 2:
            scanf("%d",&x.ord);
            x.val=heap[poz[x.ord]].val;
            pop(poz[x.ord]);
            break;
        case 3:
            printf("%d\n",heap[1].val);
        }
    }
    return 0;
}