Cod sursa(job #1316153)

Utilizator alexb97Alexandru Buhai alexb97 Data 13 ianuarie 2015 16:21:11
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.34 kb
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;

ifstream is ("heapuri.in");
ofstream os ("heapuri.out");

vector<int> D;
int cnt;

class Heap{
	public:
	Heap(int n = 0)
	 : nH(0),
	   H(vector<int>(n + 1)),
	   P(vector<int>(n + 1))
	{}
	void push(int node)
	{
		H[++nH] = node;
		P[node] = nH;
		up(node);
	}
	void pop(int node)
	{
		int p = P[node];
		int s = 2 * p;
		Swap(p, nH--);
		while(s <= nH)
		{
			if(s+1 <= nH && D[H[s]] > D[H[s+1]])
				s++;
			if(D[H[p]] > D[H[s]])
			{
				Swap(s, p);
				p = s;
				s = p * 2;
			}
			else
				break;
		}
	}
	int top()
	{
		return H[1];
	}
	int nr(int x)
	{
		return H[x];
	}
	
	private:
	void up(int node) 
	{
		int s = P[node], p = s / 2;
		while ( p != 0 && D[H[s]] < D[H[p]] ) 
		{
			Swap(s, p);	
			s = p; 
			p = s / 2;
		}
	}
	
	void Swap(int s, int p) 
	{
		swap(H[s], H[p]);
		P[H[p]] = p;
		P[H[s]] = s;
	}
	int nH;
	vector <int> H;
	vector <int> P;
};


int n;
int op;

int main()
{
	int x;
	is >> n;
	D = vector<int>(n+1);
	Heap Q(n);
	 for (int i = 1; i <= n; ++i)
    {
        is >> op;
        if (op == 1)
        {
			is >> x;
            D[++cnt] = x;
            Q.push(cnt);
        }
        if ( op == 2 )
        {   
			is >> x;
			Q.pop(x);
		}
		if ( op == 3 )
        {
            os << D[Q.top()] << '\n';
        }
    }
	is.close();
	os.close();
	return 0;
}