Cod sursa(job #348561)

Utilizator Binary_FireFlorin Pogocsan Binary_Fire Data 16 septembrie 2009 01:32:47
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.37 kb
#include <iostream>
#include <fstream>

using namespace std;

#define fin  "heapuri.in"
#define fout "heapuri.out"

#define NMAX 200010

int N, id, dim, val[NMAX], heap[NMAX], pos[NMAX];

inline void swapf(int &a, int &b) { a ^= b; b = a ^ b; a ^= b; }

void up(int nod)
{
	while ( nod / 2 && val[ heap[nod] ] < val[ heap[nod/2] ] )
	{
		swapf(heap[nod],heap[nod/2]);
		swapf(pos[ heap[nod] ],pos[ heap[nod/2] ]);
		nod /= 2;
	}
}

void sink(int nod)
{
	while ( 1 )
	{
		int nxt = 0, value = val[ heap[nod] ];

		if ( nod * 2 <= dim && value > val[ heap[2*nod] ] )
			nxt = 2*nod, value = val[ heap[2*nod] ];
		if ( 2 * nod + 1 <= dim && value > val[ heap[2*nod+1] ] )
			nxt = 2*nod + 1;

		if ( nxt )
		{
			swapf(heap[nod],heap[nxt]);
			swapf(pos[ heap[nod] ],pos[ heap[nxt] ]);

			nod = nxt;
		}
		else
			break;
	}
}

int main()
{
	int op, a;

	freopen(fin,"r",stdin);
	freopen(fout,"w",stdout);

	scanf("%d",&N);

	dim = 0;
	while ( N-- )
	{
		scanf("%d",&op);
		if ( op == 3 )
			printf("%d\n",val[ heap[1] ]);
		else
		{
			scanf("%d",&a);
			if ( op == 1 )
			{
				val[ id ] = a;
				pos[ id ] = ++dim;
				heap[ dim ] = id;
				up(dim);
				++id;
			}
			else
			{
				pos[ heap[ dim ] ] = pos[ a - 1 ];
				heap[ pos[ a - 1 ] ] = heap[ dim ];
				--dim;

				sink(pos[a-1]);
			}
		}
	}

	return 0;
}