Cod sursa(job #2893467)

Utilizator stefanliciuLiciu Vasile-Stefan stefanliciu Data 25 aprilie 2022 22:50:29
Problema Heapuri Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.6 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;
ifstream fin("heapuri.in");
ofstream fout("heapuri.out");


class Heap {
	vector<int>h;
	vector<int>ordine; //vector ce tine minte pozitiile
	vector<int>pozitie_in_heap;
	int cont;
public:
    Heap(int);
	int get_poz(int x);
	void heapify_up(int);
	void heapify_down(int);
	void insert(int);
	void del(int);
	void show_heap();
	int get_min();
	int get_ord(int x);
};

int Heap::get_ord(int x)
{
	return ordine[x];
}
int Heap::get_min()
{
	return h[0];
}
int Heap::get_poz(int x)
{
	return pozitie_in_heap[x];
}
Heap::Heap(int N)
{
	cont = 0;
	pozitie_in_heap.resize(1000000001);
	ordine.resize(N + 1);
}

void Heap::show_heap()
{
	for (auto i = this->h.begin(); i != this->h.end(); ++i)
	{
		cout << *i << ' ';
	}

	/*cout << endl << "Pozitii in heap: ";
	for (auto i = this->pozitie_in_heap.begin(); i != this->pozitie_in_heap.end(); ++i)
	{
		cout << *i << ' ';
	}
	cout << endl << "Ordine: ";
	for (auto i = this->ordine.begin(); i != this->ordine.end(); ++i)
	{
		cout << *i << ' ';
	}
	*/

}
void Heap::heapify_up(int i)
{
	if (h[(i - 1)/ 2] > h[i])
	{
		swap(h[(i - 1) / 2], h[i]);
		swap(pozitie_in_heap[h[(i - 1) / 2]], pozitie_in_heap[h[i]]);
		heapify_up((i - 1)/ 2);
	}
}

void Heap::heapify_down(int i)
{
	int left_child = 2 * i + 1;
	int right_child = 2 * i + 2;
	int small = i;
	if (left_child < h.size() && h[left_child] < h[small])
	{
		small = left_child;
	}

	if (right_child < h.size() && h[right_child] < h[small])
	{
		small = right_child;
	}

	if (small != i)
	{
		swap(h[i], h[small]);
		swap(pozitie_in_heap[h[i]], pozitie_in_heap[h[small]]);
		heapify_down(small);
	}
}

void Heap::insert(int x)
{
	h.push_back(x);
	ordine[cont++] = x;
	pozitie_in_heap[x] = h.size();
	this->heapify_up(h.size() - 1);
}

void Heap::del(int index)
{
	int x = h[index];
	//cout << "Elementul de eliminat este: " << h[index] << endl;
	swap(h[index], h[h.size() - 1]);
	//cout << h[index] << endl;
	swap(pozitie_in_heap[h[index]], pozitie_in_heap[h[h.size() - 1]]);
	h.pop_back();
	this->heapify_down(index);
	this->heapify_up(index);
	pozitie_in_heap[x] = 0;

}

int main()
{
	int N, nr_operatie, x;
	fin >> N;
	Heap H(N);

	for (int i = 0; i < N; ++i)
	{
		fin >> nr_operatie;
		if (nr_operatie == 1)
		{
			fin >> x;
			H.insert(x);
		}
		else if (nr_operatie == 2)
		{
			fin >> x;
			H.del(H.get_poz(H.get_ord(x - 1)) - 1);
		}
		else
		{
			fout << H.get_min() << '\n';
			//H.show_heap();
		    //cout << endl;
		}
	}
	return 0;
}