Cod sursa(job #2893625)

Utilizator stefanliciuLiciu Vasile-Stefan stefanliciu Data 26 aprilie 2022 14:26:08
Problema Heapuri Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.74 kb
#include <fstream>
#include <iostream>
#include <vector>
#include <unordered_map>

using namespace std;
ifstream fin("heapuri.in");
ofstream fout("heapuri.out");
#define N 200200

class Heap {
	int *h, *pozitii, *elemente; //heap de pozitii; //vector ce tine minte pozitiile in heap;
	static int numar_elemente;
	int numar_elemente_vector;

public:
	Heap();
	void heapify_up(int);
	void heapify_down(int);
	void insert(int);
	void del(int);
	void insert_element_in_vector(int);
	int get_numar_elemente_vector() { return numar_elemente_vector; }
	int get_pozitie(int x) { return pozitii[x]; }
	int get_element_din_vector(int poz) { return elemente[poz]; }
	int get_min() { return h[1]; }
	void swap_ok(int, int);
};

int Heap::numar_elemente = 0;

Heap::Heap()
{
	numar_elemente = 0;
	numar_elemente_vector = 0;
	h = new int[N]{0};
	pozitii = new int[N]{0};
	elemente = new int[N]{0};
}
void Heap::insert_element_in_vector(int x)
{
	elemente[++numar_elemente_vector] = x;
}
void Heap::swap_ok(int x1, int x2)
{
	swap(h[x1], h[x2]);
	pozitii[h[x1]] = x1;
	pozitii[h[x2]] = x2;
}

void Heap::heapify_up(int i)
{
	while (i > 1 && elemente[h[i]] < elemente[h[i / 2]])
	{
		//swap_ok(i, i / 2);
		//pozitii[heap[poz]] = poz;
		//pozitii[heap[(poz - 1) / 2]] = (poz - 1) / 2;
		swap(h[i], h[i / 2]);
		pozitii[h[i]] = i;
		pozitii[h[i/2]] = i/2;
		i /= 2;
	}
}

void Heap::heapify_down(int i)
{
	int left_child = 2 * i;
	int right_child = 2 * i + 1;
	int small = i;
	if (left_child <= numar_elemente && elemente[h[left_child] < elemente[h[small]]])
	{
		small = left_child;
	}
	if (right_child <= numar_elemente && elemente[h[right_child] < elemente[h[small]]])
	{
		small = right_child;
	}
	if (small != i)
	{
		//swap_ok(i, small);
		swap(h[i], h[small]);
		pozitii[h[i]] = i;
		pozitii[h[small]] = small;
		heapify_down(small);
	}
}

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

void Heap::del(int index)
{
	if (index == numar_elemente)
	{
		numar_elemente--;
	}
	else
	{
		h[index] = h[numar_elemente];
		numar_elemente--;
		pozitii[h[index]] = index;
		heapify_up(index);
		heapify_down(index);
	}
}

int main()
{
	int nr, nr_operatie, x;
	fin >> nr;
	Heap H;
	for (int i = 0; i < nr; ++i)
	{
		fin >> nr_operatie;
		//fout << nr_operatie << '\n';
		if (nr_operatie == 1)
		{
			fin >> x;
			//v[++nr_elem_vect] = x;
			H.insert_element_in_vector(x);
			H.insert(H.get_numar_elemente_vector());
		}
		else if (nr_operatie == 2)
		{
			fin >> x;
			H.del(H.get_pozitie(x));
		}
		else
		{
			fout << H.get_element_din_vector(H.get_min()) << '\n';
		}
	}
	fin.close();
	fout.close();
	return 0;
}