Cod sursa(job #1503969)

Utilizator vlady1997Vlad Bucur vlady1997 Data 17 octombrie 2015 10:03:47
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.48 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)]], p;
    int z=a[h[fiudr(x)]]; bool st;
    if (x*2+1>n) z=inf;
    if (y<=z) {p=y; st=true;}
    else if (x*2+1<=n && y>z) {int p=z; bool st=false;}
    if (a[h[x]]>p)
    {
        if (st)
        {
            swap(x,fiust(x));
            heapdown(fiust(x));
        }
        else
        {
            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;
}