Cod sursa(job #2296346)

Utilizator livliviLivia Magureanu livlivi Data 4 decembrie 2018 17:02:52
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.58 kb
#include<fstream>
#include<vector>
#define N 200000
using namespace std;
 
ifstream cin("heapuri.in");
ofstream cout("heapuri.out");
 
vector<bool> erased;
 
class Heap{
public:
	int value;
	int id;
 
	Heap (int a = 0, int b = 0){
		value = a;
		id = b;
	}
 
	bool operator < (Heap a){
		return (value < a.value);
	}
 
	bool isErased(){
		return erased[id];
	}
};
 
vector<Heap> heap;
 
void insertHeap(Heap x){
	heap.push_back(x);
 
	int p = heap.size() - 1;
	while(p > 0){
		if (heap[p] < heap[(p - 1) / 2]){
			swap(heap[p], heap[(p - 1) / 2]);
			p = (p - 1) / 2;
		}
		else break;
	}
}
 
void popHeap(){
	int x = heap[0].value;
 
	swap(heap[0], heap.back());
	heap.pop_back();
 
	int p = 0;
	while(p < heap.size()){
		int fiu = p;
 
		if (p * 2 + 1 < heap.size() && heap[p * 2 + 1] < heap[fiu]){
			fiu = 2 * p + 1;
		}
		if (p * 2 + 2 < heap.size() && heap[p * 2 + 2] < heap[fiu]){
			fiu = p * 2 + 2;
		}
 
		if (fiu == p) break;
 
		swap(heap[p], heap[fiu]);
		p = fiu;
	}
}
 
void insert(int x){
	while(!heap.empty() && heap[0].isErased()){
		popHeap();
	}
	
	insertHeap(Heap(x, erased.size()));
	erased.push_back(false);
}
 
void erase(int x){
	erased[x] = true;
 
	while(!heap.empty() && heap[0].isErased()){
		popHeap();
	}
}
 
int query(){
	while(!heap.empty() && heap[0].isErased()){
		popHeap();
	}
 
	if (!heap.empty()) return heap[0].value;
	else return -1;
}
 
int main(){
	int n;
	cin >> n;
 
	for(int i = 1; i <= n; i++){
		int op;
		cin >> op;
 
		if (op == 3) cout << query() << '\n';
		else {
			int x;
			cin >> x;
 
			if (op == 1) insert(x);
			if (op == 2) erase(x - 1);
		}
	}
 
	return 0;
}