Cod sursa(job #348559)

Utilizator Binary_FireFlorin Pogocsan Binary_Fire Data 16 septembrie 2009 01:25:48
Problema Heapuri Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.3 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)
{
	if ( nod == 1 )
		return ;
	if ( val[ heap[nod] ] < val[ heap[nod/2] ] )
	{
		swapf(heap[nod],heap[nod/2]);
		swapf(pos[ heap[nod] ],pos[ heap[nod/2] ]);
		up(nod/2);
	}
}

void sink(int nod)
{
	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] ]);

		sink(nxt);
	}
}

int main()
{
	int op, a;

	ifstream f1(fin);
	ofstream f2(fout);

	f1 >> N;

	dim = 0;
	while ( N-- )
	{
		f1 >> op;
		if ( op == 3 )
			f2 << val[ heap[1] ] << endl;
		else
		{
			f1 >> 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;
}