Cod sursa(job #2746678)

Utilizator vladalex420@gmail.comLuta Vlad Alexandru [email protected] Data 28 aprilie 2021 12:02:23
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.32 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <utility>
#include <algorithm>
#include <functional>


int main()
{

	std::ifstream f("heapuri.in");
	int n;
	f >> n;

	std::ofstream out("heapuri.out");

	std::vector<int> heap; // min heap;
	heap.reserve(n);

	std::vector<int> elemente;
	elemente.reserve(n);

	for (int i = 0; i < n; i++)
	{
		int op;
		f >> op;
		if (op == 1)
		{
			int x;
			f >> x;
			heap.push_back(x);
			//std::push_heap(heap.begin(), heap.end(), std::greater<int>());
				
			int pos = heap.size() - 1;
			while(pos > 0)
			{
				int parent = (pos - 1) / 2;

				if(heap[pos] < heap[parent])
				{
					std::swap(heap[pos], heap[parent]);
					pos = parent;
				}else
				{
					break;
				}
			}
			
			elemente.push_back(x);

		}else if(op == 2)
		{
			int x;
			f >> x;

			int el = elemente[x-1];

			for(int i=0;i<heap.size(); i++)
			{
				if(heap[i] == el)
				{
					//heap.erase(heap.begin() + i);
					//std::make_heap(heap.begin(), heap.end(), std::greater<int>());
					
					int pos = i;
					heap[i] = heap.back();
					heap.pop_back();
					while (true)
					{
						int leftChild = 2 * pos + 1;
						int rightChild = 2 * pos + 2;

						if(leftChild >= heap.size() && rightChild >= heap.size())
						{
							break;
						}
						else
						if(leftChild >= heap.size()) //no left child
						{
							if(heap[rightChild] < heap[pos])
							{
								std::swap(heap[rightChild], heap[pos]);
								pos = rightChild;
							}else
							{
								break;
							}
						}else
						if(rightChild >= heap.size())//no right child
						{
							if (heap[leftChild] < heap[pos])
							{
								std::swap(heap[leftChild], heap[pos]);
								pos = leftChild;
							}
							else
							{
								break;
							}
						}else
						{
							int smallerIndex = leftChild;
							if (heap[smallerIndex] > heap[rightChild]) { smallerIndex = rightChild; }

							if (heap[smallerIndex] < heap[pos])
							{
								std::swap(heap[smallerIndex], heap[pos]);
								pos = smallerIndex;
							}
							else
							{
								break;
							}
						}

					}
					
					break;
				}
			}

		}else if(op == 3)
		{
			int el = heap[0];
			out << el << "\n";

		}
	}

	out.close();

	return 0;
}