Pagini recente » Cod sursa (job #143944) | Cod sursa (job #2015084) | Cod sursa (job #359751) | Cod sursa (job #23677) | Cod sursa (job #3120844)
#include<fstream>
// #include <iostream>
#include<vector>
using namespace std;
ifstream cin("heapuri.in");
ofstream cout("heapuri.out");
class Heap {
class Node {
int value_;
int id_;
public:
Node(int value = 0, int id = 0) {
value_ = value;
id_ = id;
}
int value() const { return value_; }
int id() const { return id_; }
bool operator < (const Node& a) {
return (value_ < a.value_);
}
};
vector<bool> erased;
vector<Node> heap;
void moveup(int node);
void movedown(int node);
void cleanup();
bool isErased(int node) { return erased[heap[node].id()]; }
public:
void insert(const int value);
void erase(const int pos);
void pop();
int top();
bool empty();
};
void Heap::moveup(int node) {
while(node > 0){
if (heap[node] < heap[(node - 1) / 2]){
swap(heap[node], heap[(node - 1) / 2]);
node = (node - 1) / 2;
}
else break;
}
}
void Heap::movedown(int node){
while(node < heap.size()){
int child = node;
if (node * 2 + 1 < heap.size() && heap[node * 2 + 1] < heap[child]){
child = node * 2 + 1;
}
if (node * 2 + 2 < heap.size() && heap[node * 2 + 2] < heap[child]){
child = node * 2 + 2;
}
if (child == node) break;
swap(heap[node], heap[child]);
node = child;
}
}
void Heap::cleanup() {
while(!heap.empty() && isErased(0)){
pop();
}
}
void Heap::insert(const int value){
int id = erased.size();
// heap.push_back(Node(value, id));
heap.emplace_back(value, id);
erased.push_back(false);
moveup(heap.size() - 1);
}
void Heap::pop(){
swap(heap[0], heap.back());
heap.pop_back();
movedown(0);
}
void Heap::erase(const int pos){
erased[pos - 1] = true;
}
int Heap::top(){
cleanup();
if (!heap.empty()) return heap[0].value();
else return -1;
}
int main(){
int n; cin >> n;
Heap heap;
for(int i = 1; i <= n; i++){
int op; cin >> op;
if (op == 3) {
cout << heap.top() << '\n';
} else if (op == 1) {
int x; cin >> x;
heap.insert(x);
} else if (op == 2) {
int x; cin >> x;
heap.erase(x);
}
}
return 0;
}