Cod sursa(job #672932)

Utilizator damgoodLincan Dan damgood Data 3 februarie 2012 14:36:11
Problema Heapuri Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 2.52 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>

#include <cstdlib>

using namespace std;

vector<int> position;
int pSize;

class Heap
{
	vector<int> h;

	int father(int node)
	{
		return node / 2;
	}
	int leftSon(int node)
	{
		return node * 2;
	}
	int rightSon(int node)
	{
		return node * 2 + 1;
	}
	void sift(int node)
	{
		int son;
		do {
			son = 0;
			if( leftSon(node) <= size() )
			{
				son = leftSon(node);
				if( rightSon(node) <= size() && h[ rightSon(node) ] < h[ leftSon(node) ] )
				{
					son = rightSon(node);
				}
				if( h[son] < h[node] )
				{
					swap(h[son], h[node]);
					position[ h[son] ] = son;
					position[ h[node] ] = node;
					node = son;
				}
				else 
				{
					son = 0;
				}
			}
		} while( son );
	}
	void percolate(int node)
	{
		int value = h[node];
		
		while( (node > 1) && (h[ father(node) ] > value ) )
		{
			h[ node ] = h[ father(node) ];
			position[ h[node] ] = node;
			node = father(node);
		}
		
		h[node] = value;
		position[ h[node] ] = node;
	}
public:
	Heap(int size)
	{
		h.reserve(size + 1);
		h.push_back(0);
	}
	
	int size()
	{
		return h.size() - 1;
	}
	int getMin()
	{
		if( size() != 0 )
			return h[1];
		else
		{
			cout << "Empty heap" << endl;
			exit(1);
		}
	}
	void insert(int value)
	{
		h.push_back(value);
		percolate( size() );
	}
	void removeByPosition(int node)
	{
		h[node] = h[ size() ];
		h.pop_back();
	
		if( (node > 1) && (h[node] < h[ father(node) ]) )
			percolate(node);
		else
			sift(node);
	}
	void removeByValue(int value)
	{
		int pos = distance(h.begin(), find(h.begin(), h.end(), value) );
		removeByPosition(pos);
	}
	int get(int i)
	{
		return h[i];
	}
		
	void print()
	{
		for(int i = 1; i <= size(); ++i)
			cout << h[i] << " ";
		cout << endl;
	}
	
	friend ostream& operator<<(ostream& out, Heap &h);
};

ostream& operator<< (ostream& out, Heap &h)
	{
		out << "Heap: " << endl;
		for(int i = 1; i <= h.size(); ++i)
			out << h.get(i) << " ";
		out << endl << "========";
		return out;
	}

int main()
{
	ifstream in("heapuri.in", ifstream::in);
	ofstream out("heapuri.out");
	
	int n;
	Heap h(2048);
	in >> n;
	pSize = 210000;
	position.resize(pSize);
	vector<int> order;
	for(int i = 0; i < n; ++i)
	{
		int code, value;
		in >> code;
		switch(code)
		{
			case 1:
			{	
				in >> value;
				h.insert(value);
				order.push_back(value);
				break;
			}
			case 2:
			{
				in >> value;
				h.removeByPosition( position[ order[value - 1] ] );
				break;
			}
			case 3:
			{
				out << h.getMin() << endl;
				break;
			}
		}
	}
	return 0;
}