Cod sursa(job #1717675)

Utilizator TwoOfDiamondsDaniel Alexandru Radu TwoOfDiamonds Data 15 iunie 2016 15:09:49
Problema Heapuri Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 2.54 kb
#include <fstream>
#include <iostream>
#include <vector>

using namespace std;

class MinHeap
{
	struct nod
	{
		int key;
		int chrOrder;
	};

	vector<nod> heap;
	vector<int> position_vec;

public:

	MinHeap()
	{
		nod n; n.key = -1; n.chrOrder = -1;
		heap.push_back(n);
		position_vec.push_back(-1);
	}


	int get_min()
	{
		return heap[1].key;
	}

	void sterge(int x)
	{
		int pos = position_vec[x];

		heap[pos] = heap.back();
		heap.pop_back();

		position_vec[heap[pos].chrOrder] = pos;

		while (pos > 1 && heap[pos].key < heap[pos / 2].key)
		{

			nod a = heap[pos], b = heap[pos / 2], temp;

			position_vec[b.chrOrder] = position_vec[a.chrOrder];
			position_vec[a.chrOrder] /= 2;

			temp = heap[pos];
			heap[pos] = heap[pos / 2];
			heap[pos / 2] = temp;

			pos /= 2;
		}

		while (pos * 2 < heap.size())
		{
			int val_left, val_right;
			val_left = heap[pos * 2].key;
			if (heap.size() > pos * 2 + 1)
				val_right = heap[pos * 2 + 1].key;
			else
				val_right = 1000000001;

			if (heap[pos].key <= val_right && heap[pos].key <= val_left)
				break;

			if (val_right < val_left)
			{
				nod temp = heap[pos];
				heap[pos] = heap[pos * 2 + 1];
				heap[pos * 2 + 1] = temp;

				position_vec[heap[pos].chrOrder] = pos;
				position_vec[heap[pos * 2 + 1].chrOrder] = pos * 2 + 1;

				pos = pos * 2 + 1;
			}
			else
			{
				nod temp = heap[pos];
				heap[pos] = heap[pos * 2];
				heap[pos * 2] = temp;

				position_vec[heap[pos].chrOrder] = pos;
				position_vec[heap[pos * 2].chrOrder] = pos * 2;

				pos = pos * 2;
			}
		}

	}

	void adauga(int x)
	{
		nod nodul;
		nodul.key = x;
		nodul.chrOrder = position_vec.size();

		heap.push_back(nodul);
		position_vec.push_back(heap.size() - 1);

		int pos = heap.size() - 1;

		while (pos > 1 && heap[pos].key < heap[pos / 2].key)
		{
			
			nod a = heap[pos], b = heap[pos / 2], temp;

			position_vec[b.chrOrder] = position_vec[a.chrOrder];
			position_vec[a.chrOrder] /= 2;

			temp = heap[pos];
			heap[pos] = heap[pos / 2];
			heap[pos / 2] = temp;

			pos /= 2;
		}

	}
};


int main()
{
	ifstream in("heapuri.in");
	ofstream out("heapuri.out");

	int n; in >> n;
	MinHeap heap;

	for (int i = 0; i < n; i++)
	{
		int choice; in >> choice;
		if (choice == 1)
		{
			int x; in >> x;

			heap.adauga(x);

		}

		else if (choice == 2)
		{
			int x; in >> x;
			heap.sterge(x);
		}

		else if (choice == 3)
		{
			out << heap.get_min() << endl;
		}
	}

	return 0;
}