Cod sursa(job #3163370)

Utilizator dariustgameTimar Darius dariustgame Data 31 octombrie 2023 12:41:42
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.93 kb
#include <fstream>
#include <vector>
#include <map>

using namespace std;

ifstream fin("heapuri.in");
ofstream fout("heapuri.out");

int heap[200001];
int lenght = 0;
vector<int> nr;
map<int, int> poz;

void insertEl(int x)
{
	lenght++;
	poz[x] = lenght;
	heap[lenght] = x;
	int parent = lenght / 2;
	int pos = lenght;
	while (pos != 1 && nr[heap[parent]] > nr[heap[pos]])
	{
		swap(heap[parent], heap[pos]);
		int aux = poz[heap[parent]];
		poz[heap[parent]] = poz[heap[pos]];
		poz[heap[pos]] = aux;
		pos = parent;
		parent >>= 1;
	}
}

void delEl(int x)
{
	int i = poz[x];
	if (i == lenght)
	{
		heap[lenght] = 0;
		lenght--;
		return;
	}
	poz[heap[lenght]] = i;
	heap[i] = heap[lenght];
	heap[lenght] = 0;
	lenght--;
	int parent = i >> 1;
	int pos = i;
	while (pos != 1 && nr[heap[parent]] > nr[heap[pos]])
	{
		swap(heap[parent], heap[pos]);
		int aux = poz[heap[parent]];
		poz[heap[parent]] = poz[heap[pos]];
		poz[heap[pos]] = aux;
		pos = parent;
		parent >>= 1;
	}
	int child = pos << 1;
	if (nr[heap[child]] < nr[heap[child + 1]])
	{
		parent = child;
	}
	else
	{
		parent = child + 1;
	}
	if (child + 1 > lenght) parent = child;
	while (child <= lenght && nr[heap[child]] < nr[heap[pos]])
	{
		swap(heap[parent], heap[pos]);
		int aux = poz[heap[parent]];
		poz[heap[parent]] = poz[heap[pos]];
		poz[heap[pos]] = aux;
		pos = parent;
		child = pos << 1;
		if (nr[heap[child]] < nr[heap[child + 1]])
		{
			parent = child;
		}
		else
		{
			parent = child + 1;
		}
		if (child + 1 > lenght) parent = child;
	}
}

int minEl()
{
	return nr[heap[1]];
}

int main()
{
	int n;
	fin >> n;
	int x, y;
	nr.push_back(0);
	for (int i = 0; i < n; i++)
	{
		fin >> x;
		if (x != 3)
		{
			fin >> y;
		}
		if (x == 1)
		{
			nr.push_back(y);
			insertEl(nr.size() - 1);
		}
		else if (x == 2)
		{
			delEl(y);
		}
		else
		{
			fout << minEl() << '\n';
		}
	}
}