Pagini recente » Cod sursa (job #60964) | Cod sursa (job #1102571) | Cod sursa (job #1776755) | Cod sursa (job #2521778) | Cod sursa (job #2890769)
#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 > 1)
{
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 (2 * index + 1 < storage.size() && storage[2 * index] > storage[2 * index + 1])
{
swap(indices[storage[index]], indices[storage[2 * index + 1]]);
swap(storage[index], storage[2 * index + 1]);
index = 2 * index + 1;
}
else if (2 * index < storage.size())
{
swap(indices[storage[index]], indices[storage[2 * index]]);
swap(storage[index], storage[2 * index]);
index = 2 * index;
}
}
}
public:
Heap()
{
storage.emplace_back(T());
}
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() == 1)
throw out_of_range("Heap is Empty");
return storage[1];
}
void remove(size_t nth_elem)
{
size_t index = indices[elements[nth_elem - 1]];
if (storage.size() == 1)
throw out_of_range("Heap is Empty");
indices[storage.back()] = indices[storage[index]];
storage[index] = storage.back();
storage.pop_back();
if (index < storage.size())
{
floatUp(index);
floatDown(index);
}
}
};
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();
}