Cod sursa(job #1799131)

Utilizator demetriad-dagpagDavid Demetriad demetriad-dagpag Data 5 noiembrie 2016 20:04:00
Problema Heapuri Scor 100
Compilator c Status done
Runda Arhiva educationala Marime 1.31 kb
#include <stdio.h>
#include <stdlib.h>
int v[200001],heap[200001],pos[200001];
void push(int x)
{
    int aux;
    while(x/2 && v[heap[x]]<v[heap[x/2]])
    {
        aux=heap[x];
        heap[x]=heap[x/2];
        heap[x/2]=aux;
        pos[heap[x]]=x;
        pos[heap[x/2]]=x/2;
        x/=2;
    }
}
void pull(int x,int e)
{
    int aux,y=0;
    while(x!=y)
    {
        y=x;
        if(y*2<=e && v[heap[x]]>v[heap[y*2]]) x=y*2;
        if(y*2+1<=e && v[heap[x]]>v[heap[y*2+1]]) x=y*2+1;
        aux=heap[x];
        heap[x]=heap[y];
        heap[y]=aux;
        pos[heap[x]]=x;
        pos[heap[y]]=y;
    }
}
int main()
{
    int x,nr,e,i,n,q;
    freopen("heapuri.in","r",stdin);
    freopen("heapuri.out","w",stdout);
    scanf("%d",&n);
    nr=0;
    e=0;
    for(i=1; i<=n; i++)
    {
        scanf("%d",&q);
        if(q==3)
            printf("%d\n",v[heap[1]]);
        if(q==1)
        {
            heap[++e]=++nr;
            scanf("%d",&x);
            v[nr]=x;
            pos[nr]=e;
            push(e);
        }
        if(q==2)
        {
            scanf("%d",&x);
            v[x]=-1;
            push(pos[x]);
            heap[1]=heap[e];
            pos[heap[1]]=pos[heap[e]];
            e--;
            pull(1,e);
        }
    }

    return 0;
}