Cod sursa(job #314365)

Utilizator QbyxEros Lorand Qbyx Data 11 mai 2009 17:36:53
Problema Heapuri Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.17 kb
#include <iostream>
#define NMAX 200002

using namespace std;

int heap[NMAX], kr[NMAX], poz[NMAX], n, hh = 0, m, k, x;

void swap(int &a, int &b)
{
    int c = a;
    a = b;
    b = c;
}

void push(int x)
{
    for (int i = hh; i > 1 && heap[i] < heap[i >> 1]; i >>= 1)
	{
	    swap(heap[i], heap[i >> 1]);
	    swap(kr[poz[i >> 1]], kr[poz[i]]);
	    swap(poz[i >> 1], poz[i]);
	}
}

void pop(int y)
{
    int f, i = kr[y];

    heap[i] = 1000000001;
    do
    {
	f = 0;
	if (i << 1 <= hh)
	    f = i << 1;
	if ((i << 1) + 1 <= hh && heap[(i << 1) + 1] < heap[i << 1])
	    f++;

	if (f)
	{
	    swap(heap[i], heap[f]);
	    swap(kr[poz[i]], kr[poz[f]]);
	    swap(poz[i], poz[f]);
	    i = f;
	}
    }
    while (f);
}

int main()
{
    freopen("heapuri.in", "rt", stdin);
    freopen("heapuri.out", "wt", stdout);

    cin >> n;
    int i = 0;
    for ( ; n; --n)
    {
	cin >> k;
	switch(k)
	{
	    case 1: 
		{
		    cin >> x;
		    heap[++hh] = x;
		    kr[++i] = hh;
		    poz[hh] = i;
		    push(x);
		    break;
		}
	    case 2:
		{
		    cin >> x;
		    pop(x);
		    kr[x] = 0;
		    hh--;
		    break;
		}
	    case 3:
		{
		    cout << heap[1] << endl;
		    break;
		}
	}
    }
}