Cod sursa(job #2738952)

Utilizator vali_27Bojici Valentin vali_27 Data 6 aprilie 2021 16:38:22
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.44 kb
#include <iostream>
#include <fstream>
#include <vector>

int v[200000], h[200000], poz[200000], heap_size, vals_size;

int getIdxChild(int index)
{
	int left = index * 2 + 1, right = index * 2 + 2;
	if (right < heap_size)
		return v[h[left]] <= v[h[right]] ? left : right;
	return left;
}



void downHeap(int index)
{
	while (index < heap_size / 2)
	{
		int child = getIdxChild(index);
		if (v[h[child]] < v[h[index]])
		{
			std::swap(h[child], h[index]);
			poz[h[child]] = child;
			poz[h[index]] = index;
			index = child;
		}
		else return;
	}
}


void upHeap(int index)
{
	while (index > 0 && v[h[index]] < v[h[(index - 1) / 2]])
	{
		std::swap(h[index], h[(index - 1) / 2]);
		poz[h[index]] = index;
		poz[h[(index - 1) / 2]] = (index - 1) / 2;
		index = (index - 1) / 2;
	}
}



void insert(int x)
{
	h[heap_size++] = vals_size;
	v[vals_size++] = x;
	poz[vals_size - 1] = heap_size - 1;
	upHeap(heap_size - 1);
}


void deleteAt(int index)
{
	h[poz[index]] = h[heap_size - 1];
	poz[h[poz[index]]] = poz[index];
	heap_size--;
	downHeap(poz[index]);
	upHeap(poz[index]);
}


int main()
{
	std::ifstream f("heapuri.in");
	std::ofstream g("heapuri.out");
	int n;
	f >> n;

	for (int i = 0; i < n; ++i)
	{
		int op, x;
		f >> op;
		if (op == 1)
		{
			f >> x;
			insert(x);
		}
		else if (op == 2)
		{
			f >> x;
			deleteAt(x - 1);
		}
		else
		{
			g << v[h[0]] << '\n';
		}
	}
}