Cod sursa(job #1386643)

Utilizator vlady1997Vlad Bucur vlady1997 Data 13 martie 2015 09:49:07
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.36 kb
#include <cstdio>
#define tata(x)  x/2
#define fiust(x) x*2
#define fiudr(x) x*2+1
using namespace std;
int a[200001], h[200001], poz[200001], n=0, m=0;
void swap (int x, int y)
{
    poz[h[x]]=y;
    poz[h[y]]=x;
    int aux=h[x];
    h[x]=h[y];
    h[y]=aux;
}
void heapup (int x)
{
    if (x==1) return;
    if (a[h[tata(x)]]>a[h[x]])
    {
        swap(x,tata(x));
        heapup(tata(x));
    }
}
void heapdown (int x)
{
    int valst=-1, valdr=-1, p;
    if (fiust(x)>n) return;
    valst=a[h[fiust(x)]];
    if (fiudr(x)<=n) valdr=a[h[fiudr(x)]];
    else valdr=valst+1;
    if (valst<=valdr) p=fiust(x);
    else p=fiudr(x);
    if(a[h[tata(p)]]>a[h[p]])
    {
        swap(p,tata(p));
        heapdown(p);
    }
}
int main()
{
    int t, i, p, k, x, y;
    freopen("heapuri.in","r",stdin);
    freopen("heapuri.out","w",stdout);
    scanf("%d",&t);
    for (i=1; i<=t; i++)
    {
        scanf("%d",&p);
        if (p==1)
        {
            scanf("%d",&x);
            a[++m]=x;
            h[++n]=m;
            poz[m]=n;
            heapup(n);
        }
        else if (p==2)
        {
            scanf("%d",&k);
            y=poz[k];
            swap(poz[k],n);
            n--;
            heapdown(y);
        }
        else
        {
            printf("%d\n",a[h[1]]);
        }
    }
    return 0;
}