Cod sursa(job #1503951)

Utilizator vlady1997Vlad Bucur vlady1997 Data 17 octombrie 2015 09:46:18
Problema Heapuri Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.35 kb
#include <cstdio>
#define inf 2000000000
#define tata(x)  x/2
#define fiust(x) x*2
#define fiudr(x) x*2+1
using namespace std;
int h[200001], a[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)
{
    if (x*2>n) return;
    int y=a[h[fiust(x)]];
    int z=a[h[fiudr(x)]];
    if (x*2+1>n) z=inf;
    if (a[h[x]]>y && a[h[x]]<z)
    {
        swap(x,fiust(x));
        heapdown(fiust(x));
    }
    else if (a[h[x]]>z)
    {
        swap(x,fiudr(x));
        heapdown(fiudr(x));
    }
}
int main()
{
    int t, i, p, x, k;
    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",&x); k=poz[x];
            swap(poz[x],n); n--;
            heapdown(k);
        }
        else
        {
            printf("%d\n",a[h[1]]);
        }
    }
    return 0;
}