Pagini recente » Cod sursa (job #2982244) | Cod sursa (job #2796134) | Cod sursa (job #2088839) | Cod sursa (job #3163882) | Cod sursa (job #2666299)
#include <iostream>
#include <fstream>
#include <stdexcept>
const int NMAX = 2e5;
struct HeapNode {
int val;
int insertIndex;
};
int heapSize = 1;
HeapNode heap[1 + NMAX];
int heapPos[1 + NMAX];
inline int bubble_up(int index) {
int parent = index / 2;
while (index > 1 && heap[index].val < heap[parent].val) {
heapPos[heap[parent].insertIndex] = index;
std::swap(heap[index], heap[parent]);
index = parent;
parent = index / 2;
}
return index;
}
inline int bubble_down(int index) {
int leftChild = index * 2;
int rightChild = index * 2 + 1;
int minChild = leftChild;
if (rightChild < heapSize && heap[rightChild].val < heap[leftChild].val)
minChild = rightChild;
while (minChild < heapSize && heap[minChild].val < heap[index].val) {
heapPos[heap[minChild].insertIndex] = index;
std::swap(heap[minChild], heap[index]);
index = minChild;
leftChild = index * 2;
rightChild = index * 2 + 1;
minChild = leftChild;
if (rightChild < heapSize && heap[rightChild].val < heap[leftChild].val)
minChild = rightChild;
}
return index;
}
void insert(const HeapNode& node) {
heap[heapSize] = node;
heapPos[node.insertIndex] = bubble_up(heapSize);
++heapSize;
}
void remove(int index) {
heapPos[heap[heapSize - 1].insertIndex] = index;
std::swap(heap[index], heap[heapSize - 1]);
--heapSize;
index = bubble_up(index);
heapPos[heap[index].insertIndex] = bubble_down(index);
}
void printHeap() {
for (int i = 1; i <= heapSize; ++i)
std::cout << heap[i].val << ' ' << heap[i].insertIndex << ", ";
std::cout << '\n';
for (int i = 1; i <= 4; ++i)
std::cout << heapPos[i] << " ";
std::cout << "\n\n";
}
int main() {
std::ifstream in("heapuri.in");
std::ofstream out("heapuri.out");
int n;
int index = 1;
in >> n;
int op, val;
for (int i = 1; i <= n; ++i) {
in >> op;
switch (op) {
case 1:
in >> val;
insert({val, index});
++index;
break;
case 2:
in >> val;
remove(heapPos[val]);
break;
case 3:
out << heap[1].val << '\n';
break;
default:
throw std::runtime_error("...");
}
// printHeap();
}
return 0;
}