Cod sursa(job #1654465)

Utilizator andreioneaAndrei Onea andreionea Data 17 martie 2016 03:22:53
Problema Heapuri Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.2 kb
#include <fstream>
#include <vector>
#include <algorithm>

uint32_t find_special(const std::vector<uint32_t>& vec, int pos, int val)
{
	if (pos >= vec.size())
		return vec.size();
	if (vec[pos] == val)
		return pos;
	if (vec[pos] > val)
		return vec.size();
	const auto look_left = find_special(vec, pos * 2 + 1, val);
	if (look_left < vec.size())
		return look_left;
	return find_special(vec, pos * 2 + 2, val);

}

int main()
{
	std::ifstream f("heapuri.in");
	std::ofstream g("heapuri.out");
	std::vector<uint32_t> heap;
	std::vector<uint32_t> vec; 
	uint32_t N;
	uint32_t code, val;
	f >> N;
	heap.reserve(N);
	vec.reserve(N);
	while (N--)
	{
		f >> code;
		if (code == 3)
		{
			std::make_heap(heap.begin(), heap.end(), std::greater<uint32_t>());
			g << heap.front() << "\n";
		}
		else
		{
			f >> val;
			if (code == 1)
			{
				heap.push_back(val);
				std::push_heap(heap.begin(), heap.end(), std::greater<uint32_t>());
				vec.push_back(val);
			}
			else
			{
				const auto valToFind = vec[val - 1];
				auto it = heap.begin() + find_special(heap, 0, valToFind);
				*it = heap.back();
				heap.pop_back();
				std::make_heap(it, heap.end(), std::greater<uint32_t>());
			}
		}
	}
	f.close();
	g.close();
	return 0;
}