Cod sursa(job #2893607)

Utilizator stefanliciuLiciu Vasile-Stefan stefanliciu Data 26 aprilie 2022 13:24:23
Problema Heapuri Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.55 kb
#include <iostream>
#include <fstream>

using namespace std;

ifstream fin("heapuri.in");
ofstream fout("heapuri.out");
#define N 200005

int numar_elemente;
int pozitii[N], heap[N], v[N];

void swap_ok(int a, int b)
{
	swap(heap[a], heap[b]);
	pozitii[heap[a]] = a;
	pozitii[heap[b]] = b;
}

void heapify_up(int poz)
{
	while (poz > 1 && v[heap[poz]] < v[heap[poz/ 2]])
	{
		swap_ok(poz, poz / 2);
		poz /= 2;
	}
}

void  heapify_down(int i)
{
	int left_child = 2 * i;
	int right_child = 2 * i + 1;
	int small = i;
	if (left_child <= numar_elemente && v[heap[left_child] < v[heap[small]]])
	{
		small = left_child;
	}
	if (right_child <= numar_elemente && v[heap[right_child] < v[heap[small]]])
	{
		small = right_child;
	}
	if (small != i)
	{
		swap_ok(i, small);
		heapify_down(small);
	}
}

void insert(int x)
{
	heap[++numar_elemente] = x;
	pozitii[x] = numar_elemente;
	heapify_up(numar_elemente);
}

void del(int i)
{
	if (i == numar_elemente)
	{
		numar_elemente--;
	}
	else
	{
		heap[i] = heap[numar_elemente--];
		pozitii[heap[i]] = i;
		heapify_up(i);
		heapify_down(i);
	}
}
int main()
	{
		int nr, nr_operatie, x, nr_elem_vect = 0;
		fin >> nr;
		for (int i = 0; i < nr; ++i)
		{
			fin >> nr_operatie;
			if (nr_operatie == 1)
			{
				fin >> x;
				v[++nr_elem_vect] = x;
				insert(nr_elem_vect);
			}
			else if (nr_operatie == 2)
			{
				fin >> x;
				del(pozitii[x]);
			}
			else
			{
				fout << v[heap[1]] << '\n';
			}
		}
		fin.close();
		fout.close();
		return 0;
}