Cod sursa(job #2734449)

Utilizator vali_27Bojici Valentin vali_27 Data 31 martie 2021 21:50:38
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
		{
			break;
		}
	}
}

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)
{
	v[index] = -1;
	upHeap(poz[index]);
	h[0] = h[heap_size - 1];
	poz[h[0]] = 0;
	heap_size--;
	downHeap(0);
}

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';
		}
	}
}