Cod sursa(job #1386619)

Utilizator vlady1997Vlad Bucur vlady1997 Data 13 martie 2015 09:33:07
Problema Heapuri Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.46 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;
    if (fiust(x)>n) return;
    if (a[h[x]]>a[h[fiust(x)]]) valst=a[h[fiust(x)]];
    if (fiudr(x)<=n)
    {
        if (a[h[x]]>a[h[fiudr(x)]]) valdr=a[h[fiudr(x)]];
    }
    if (valdr==-1 || valst<valdr)
    {
        swap(x,fiust(x));
        heapdown(fiust(x));
    }
    else if (valdr<valst)
    {
        swap(x,fiudr(x));
        heapup(fiudr(x));
    }
}
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;
}