Cod sursa(job #505213)

Utilizator AndrewTheGreatAndrei Alexandrescu AndrewTheGreat Data 1 decembrie 2010 00:51:51
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.54 kb
#include <iostream>
#include <stdio.h>
#define maxn 200005
using namespace std;

int val[maxn], H[maxn], poz[maxn], L, last;
int tata, aux, st, dr;

void upheap(int p)
{
    tata = p >> 1;
    while(val[H[p]] < val[H[tata]] && tata)
    {
        aux = H[p];
        H[p] = H[tata];
        H[tata] = aux;

        poz[H[p]] = p;
        poz[H[tata]] = tata;
        p = tata;
        tata = p >> 1;
    }
}

void downheap(int p)
{
    tata = p;
    do {
        p = tata;
        st = tata << 1;
        dr = st + 1;
        if(val[H[st]] < val[H[tata]] && st <= L)
            tata = st;

        if(val[H[dr]] < val[H[tata]] && dr <= L)
            tata = dr;

        if(tata != p)
        {
            aux = H[tata];
            H[tata] = H[p];
            H[p] = aux;

            poz[H[p]] = p;
            poz[H[tata]] = tata;
        }
    } while (p != tata);
}

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

    int N, x, o;
    scanf("%d", &N);
    while(N--)
    {
        scanf("%d",&o);
        if(o == 1){
            scanf("%d",&x);
            val[++last] = x;
            poz[last] = ++L;
            H[L] = last;
            upheap(L);
        }

        if(o == 2){
            scanf("%d",&x);
            H[poz[x]] = H[L];
            poz[H[poz[x]]] = poz[x];
            L--;
            upheap(poz[x]);
            downheap(poz[x]);
        }

        if(o == 3)
            printf("%d\n",val[H[1]]);
    }
    return 0;
}