Cod sursa(job #731911)

Utilizator repp4raduRadu-Andrei Szasz repp4radu Data 9 aprilie 2012 13:55:34
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.75 kb
#include <stdio.h>
#include <algorithm>

using namespace std;

const int MAX = 200005;
int a[MAX], pos[MAX], heap[MAX], nr, l, n, op, x;

void percolate(int x)
{
    while((x / 2) && a[heap[x]] < a[heap[x / 2]])
    {
        swap(heap[x], heap[x / 2]);
        pos[heap[x]] = x;
        pos[heap[x / 2]] = x / 2;
        x >>= 1;
    }
}

void sift(int x)
{
    int Eson = 0, son;
    do
    {
        Eson = 0;
        son = 2 * x;
        if(son <= l && a[heap[son]] < a[heap[x]])
            Eson = son;
        son++;
        if(son <= l)
        {
            if(Eson)
            {
                if(a[heap[son]] < a[heap[Eson]])
                    Eson = son;
            }
            else
            {
                if(a[heap[son]] < a[heap[x]])
                    Eson = son;
            }
        }
        if(Eson)
        {
            swap(heap[Eson], heap[x]);
            pos[heap[Eson]] = Eson;
            pos[heap[x]] = x;
        }
        x = Eson;
    }while(Eson);
}

int main()
{
    freopen("heapuri.in", "r", stdin);
    freopen("heapuri.out", "w", stdout);
    scanf("%d", &n);
    while(n--)
    {
        scanf("%d", &op);
        if(op < 3)
        {
            scanf("%d", &x);
            if(op == 1)
            {
                a[++nr] = x;
                heap[++l] = nr;
                pos[nr] = l;
                percolate(l);
            }
            else
            {
                a[x] = -1;
                percolate(pos[x]);
                heap[1] = heap[l--];
                pos[x] = 0;
                pos[heap[1]] = 1;
                sift(1);
            }
        }
        else
            printf("%d\n", a[heap[1]]);
    }
    return 0;
}