Cod sursa(job #2372038)

Utilizator maria_sinteaMaria Sintea maria_sintea Data 6 martie 2019 21:01:06
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.36 kb
#include <iostream>
#include <cstdio>
#define N 200005

using namespace std;

int n, op, nr, na, nh, a[N], h[N], poz[N];

void adaug(int x)
{
    int aux;
    while(x/2 && a[h[x]]<a[h[x/2]])
    {
        aux=h[x];
        h[x]=h[x/2];
        h[x/2]=aux;
        poz[h[x]]=x;
        poz[h[x/2]]=x/2;
        x=x/2;
    }
}

void sterg(int x)
{
    int aux, y=0;
    while(x!=y)
    {
        y=x;
        if(y*2<=nh && a[h[x]]>a[h[y*2]])
            x=y*2;
        if(y*2+1<=nh && a[h[x]]>a[h[y*2+1]])
            x=y*2+1;

		aux=h[x];
		h[x]=h[y];
		h[y]=aux;
		poz[h[x]]=x;
		poz[h[y]]=y;
    }
}

int main()
{
    freopen("heapuri.in", "r", stdin);
    freopen("heapuri.out", "w", stdout);

    scanf("%d\n", &n);
    for(int i=0;i<n;i++)
    {
        scanf("%d ", &op);
        if(op==1)
        {
            scanf("%d\n", &nr);
            a[++na]=nr;
            h[++nh]=na;
            poz[na]=nh;
            adaug(nh);
        }
        else
            if(op==2)
            {
                scanf("%d\n", &nr);
                a[nr]=-1;
                adaug(poz[nr]);

                poz[h[1]]=0;
                h[1]=h[nh--];
                poz[h[1]]=1;
                if(nh>1)
                    sterg(1);
            }
        else
            printf("%d\n", a[h[1]]);
    }
    return 0;
}