Pagini recente » Cod sursa (job #1551780) | Cod sursa (job #2097788) | Cod sursa (job #2251444) | Cod sursa (job #1138469) | Cod sursa (job #1986591)
#include <iostream>
#include <fstream>
using namespace std;
ifstream in("heapuri.in");
ofstream out("heapuri.out");
class Heap {
public:
int *position, *order;
int insertions = 0;
Heap(int n) {
size = 0;
maxsize = n;
tree = new int[n + 1];
position = new int[n + 1];
order = new int[n + 1];
}
int Peek() {
return tree[1];
}
void Insert(int val) {
insertions++;
size++;
tree[size] = val;
position[insertions] = size;
order[size] = insertions;
heapify_up(size);
}
void Remove(int pos) {
int index = position[pos];
tree[index] = tree[size];
size--;
heapify_down(index);
}
private:
int *tree, size, maxsize;
inline int get_parent(int index) {
return index / 2;
}
inline int get_left_child(int index) {
return index * 2;
}
inline int get_right_child(int index) {
return index * 2 + 1;
}
inline bool has_left_child(int index) {
return get_left_child(index) <= size;
}
inline bool has_right_child(int index) {
return get_right_child(index) <= size;
}
void swap_nodes(int a, int b) {
swap(tree[a], tree[b]);
position[order[a]] = b;
position[order[b]] = a;
swap(order[a], order[b]);
}
void heapify_up(int index) {
while (index > 1 && tree[index] < tree[get_parent(index)]) {
swap_nodes(index, get_parent(index));
index = get_parent(index);
}
}
void heapify_down(int index) {
while (has_left_child(index)) {
int lower_child = get_left_child(index);
if (has_right_child(index) && tree[get_right_child(index)] < tree[lower_child]) {
lower_child = get_right_child(index);
}
if (tree[index] > tree[lower_child]) {
swap_nodes(index, lower_child);
index = lower_child;
} else {
break;
}
}
}
};
Heap *H;
int n;
int main() {
in >> n;
H = new Heap(200000);
for (int i = 1, o, x; i <= n; ++i) {
in >> o;
if (o == 3) {
out << H -> Peek() << '\n';
} else {
in >> x;
if (o == 1) {
H -> Insert(x);
} else {
H -> Remove(x);
}
}
}
}