Cod sursa(job #2893549)

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

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


class Heap {
	vector<int>h;
	vector<int>ordine; //vector ce tine minte ordinea
	unordered_map<int, int>pozitie_in_heap;
public:
	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];
}

void Heap::show_heap()
{
	for (auto i = this->h.begin(); i != this->h.end(); ++i)
	{
		cout << *i << ' ';
	}
}
void Heap::heapify_up(int i)
{
		while (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]]);
			i = (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.push_back(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]);
	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;

	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;
		}
	}
	fin.close();
	fout.close();
	return 0;
}