Cod sursa(job #3163341)

Utilizator dariustgameTimar Darius dariustgame Data 31 octombrie 2023 12:02:51
Problema Heapuri Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.77 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++;
	nr.push_back(x);
	poz[x] = lenght;
	heap[lenght] = x;
	int parent = lenght / 2;
	int pos = lenght;
	while (pos != 1 && heap[parent] > 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 n = nr[x - 1];
	int i = poz[n];
	poz[heap[lenght]] = i;
	heap[i] = heap[lenght];
	heap[lenght] = 0;
	lenght--;
	int parent = i >> 1;
	int pos = i;
	while (pos != 1 && heap[parent] > 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 (heap[child] < heap[child + 1])
	{
		parent = child;
	}
	else
	{
		parent = child + 1;
	}
	if (child + 1 > lenght) parent = child;
	while (child <= lenght && heap[child] < 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 (heap[child] < heap[child + 1])
		{
			parent = child;
		}
		else
		{
			parent = child + 1;
		}
		if (child + 1 > lenght) parent = child;
	}
}

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

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