Pagini recente » Cod sursa (job #2554737) | Cod sursa (job #456452) | Cod sursa (job #1542156) | Cod sursa (job #56556) | Cod sursa (job #3121361)
#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:
Heap() {
heap.resize(1);
}
void insert(const int value);
void erase(const int pos);
void pop();
int top();
bool empty();
};
void Heap::moveup(int node) {
while(node > 1){
if (heap[node] < heap[node / 2]){
swap(heap[node], heap[node / 2]);
node = node / 2;
}
else break;
}
}
void Heap::movedown(int node){
while(node < heap.size()){
int child = node;
if (node * 2 < heap.size() && heap[node * 2] < heap[child]){
child = node * 2;
}
if (node * 2 + 1 < heap.size() && heap[node * 2 + 1] < heap[child]){
child = node * 2 + 1;
}
if (child == node) break;
swap(heap[node], heap[child]);
node = child;
}
}
void Heap::cleanup() {
while(!heap.empty() && isErased(1)){
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[1], heap.back());
heap.pop_back();
movedown(1);
}
void Heap::erase(const int pos){
erased[pos - 1] = true;
}
int Heap::top(){
cleanup();
if (!heap.empty()) return heap[1].value();
else return -1;
}
bool Heap::empty() {
cleanup();
return heap.empty();
}
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;
}