Cod sursa(job #2734438)

Utilizator vali_27Bojici Valentin vali_27 Data 31 martie 2021 21:09:36
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.43 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(poz[h[child]], poz[h[index]]);
			std::swap(h[child], h[index]);
			index = child;
		}
		else
		{
			break;
		}
	}
}

void upHeap(int index)
{
	while (index > 0 && v[h[index]] < v[h[(index - 1) / 2]])
	{
		std::swap(poz[h[index]], poz[h[(index - 1) / 2]]);
		std::swap(h[index], h[(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)
{
	std::swap(h[poz[index]], h[heap_size - 1]);
	poz[h[poz[index]]] = poz[index];

	heap_size--;
	downHeap(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';
		}
	}
}