Cod sursa(job #2890750)

Utilizator widzAndrei-Daniel Tava widz Data 16 aprilie 2022 14:47:22
Problema Heapuri Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.08 kb
#include <fstream>
#include <iostream>
#include <vector>
#include <unordered_map>

using namespace std;

template <class T>
class Heap
{
private:
	vector<T> storage;
	vector<size_t> elements;
	unordered_map<size_t, size_t> indices;
	void floatUp(size_t index)
	{
		while (storage[index] < storage[index / 2] && index > 0)
		{
			swap(indices[storage[index]], indices[storage[index / 2]]);
			swap(storage[index],storage[index / 2]);
			index /= 2;
		}
	}
	void floatDown(size_t index)
	{
		while(2 * index < storage.size() && storage[index] > storage[2*index] || 2 * index + 1 < storage.size() && storage[index] > storage[2 * index + 1])
		{
			if (storage[2 * index] < storage[2 * index + 1])
			{
				swap(indices[storage[index]], indices[storage[2 * index]]);
				swap(storage[index], storage[2 * index]);
				index = 2 * index;
			}
			else
			{
				swap(indices[storage[index]], indices[storage[2 * index + 1]]);
				swap(storage[index], storage[2 * index + 1]);
				index = 2 * index + 1;
			}
		}
	}
public:
	void insert(T item)
	{
		storage.push_back(item);
		elements.push_back(item);
		indices[item] = storage.size() - 1;
		floatUp(indices[item]);
	}
	T getMin() const
	{
		if (storage.size() == 0)
			throw out_of_range("Heap is Empty");
		return storage[0];
	}
	void remove(size_t nth_elem)
	{
		size_t index = indices[elements[nth_elem - 1]];
		if (storage.size() == 0)
			throw out_of_range("Heap is Empty");
		indices.erase(storage.back());
		storage[index] = storage.back();
		storage.pop_back();
		floatUp(storage.size() - 1);
		floatDown(storage.size() - 1);
	}
};


int main()
{
	ifstream in("heapuri.in");
	ofstream out("heapuri.out");
	Heap<size_t> heap;
	unsigned int nr_op;
	char command;
	size_t argument;
	in >> nr_op;
	for(unsigned int i=0; i<nr_op;++i)
	{
		in >> command;
		switch (command)
		{
		case '3':
			out << heap.getMin()<<'\n';
			break;
		case '2':
			in >> argument;
			heap.remove(argument);
			break;
		case '1':
			in >> argument;
			heap.insert(argument);
		}

	}
	in.close();
	out.close();
}