Cod sursa(job #1875236)

Utilizator xtreme77Patrick Sava xtreme77 Data 10 februarie 2017 21:14:01
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.63 kb
#include <fstream>
#include <vector>
#include <cassert>
#include <bitset>

using namespace std ;

ifstream cin ("heapuri.in") ;
ofstream cout ("heapuri.out") ;

const int MAX = 200014 ;
int v [MAX] , cate ;
bitset <MAX> viz ;

class Heap {
	public :
	Heap (int n)
	{
		h.resize(n) ;
	}
	int Top()
	{
		assert (sz>0) ;
		if (viz[h[1]] == 0)
			return v[h[1]] ;
		else {
			this->Pop() ;
			return Top() ;
		}
	}
	void Pop()
	{
		swap (h[1], h[sz]) ;
		sz -- ; 
		Down(1);
	}
	void Push(int x)
	{
		++ sz ;
		h [sz] = x ;
		Up(sz) ;
 	}
	private :
	vector < int > h ;
	int sz ;
	void Up(int nod)
	{
		while (nod / 2 >= 1) {
			if (v[h [nod/2]] > v[h[nod]]){
				swap (h[nod/2], h[nod]);
				nod >>= 1 ;
			}
			else {
				break ;
			}
		}
	}
	void Down(int nod)
	{
		while (nod * 2 <= sz) {
			if (nod * 2 + 1 <= sz and v[h[nod]]>v[h[nod<<1]] and v[h[nod]]>v[h[nod<<1|1]]){
				if (v[h[nod<<1]]<v[h[nod<<1|1]]) {
					swap(h[nod<<1], h[nod]);
					nod <<= 1 ;
				}
				else {
					swap(h[nod<<1|1], h[nod]);
					nod <<= 1 ;
					nod |= 1 ;
				}
				continue ;
			}
			if (v[h[nod]]>v[h[nod<<1]]) {
				swap(h[nod<<1], h[nod]);
				nod <<= 1 ;
				continue ;
			}
			if (nod * 2 + 1 <= sz and v[h[nod]]>v[h[nod<<1|1]]) {
				swap(h[nod<<1|1], h[nod]);
				nod <<= 1 ;
				nod |= 1 ;
				continue ;
			}
			break ;
		}
	}
};

int main ()
{
	int n ; 
	cin >> n ;
	Heap *H = new Heap(n+5) ;
	while (n --) 
	{
		int tip ; 
		cin >> tip ; 
		if ( tip == 1 ) {
			int x ; 
			cin >> x ; 
			++ cate ;
			v [cate] = x ;
			H -> Push(cate) ;
		}
		else if (tip == 2) {
			int x ; 
			cin >> x ; 
			viz [x] = 1 ; 
		}
		else {
			cout << H->Top() << '\n' ;
		}
	}
	return 0 ;
}