Pagini recente » Cod sursa (job #1664561) | Cod sursa (job #1511671) | Cod sursa (job #2353221) | Cod sursa (job #2535032) | Cod sursa (job #3252656)
#include <iostream>
#include <fstream>
using namespace std;
const int MAX_SIZE = 200000;
int heap[MAX_SIZE + 1]; // Min-heap array
int elements[MAX_SIZE + 1]; // Array to store elements in insertion order
int heapSize = 0; // Size of the min-heap
int elementCount = 0; // Total count of elements inserted
// Helper function to swap two elements in the heap
void swap(int &a, int &b) {
int temp = a;
a = b;
b = temp;
}
// Function to insert an element into the min-heap
void insertHeap(int index) {
heap[++heapSize] = index; // Insert the index of the new element
int i = heapSize;
while (i > 1 && elements[heap[i]] < elements[heap[i / 2]]) {
swap(heap[i], heap[i / 2]);
i /= 2;
}
}
// Function to delete an element from the heap by index
void deleteFromHeap(int index) {
// Find the position of the element to delete in the heap
int position = -1;
for (int i = 1; i <= heapSize; i++) {
if (heap[i] == index) {
position = i;
break;
}
}
if (position == -1) return; // Element not found (should not happen as per problem statement)
// Swap the element with the last element in the heap
swap(heap[position], heap[heapSize--]);
// Restore heap property by heapifying down
int i = position;
while (true) {
int smallest = i;
if (2 * i <= heapSize && elements[heap[2 * i]] < elements[heap[smallest]]) {
smallest = 2 * i;
}
if (2 * i + 1 <= heapSize && elements[heap[2 * i + 1]] < elements[heap[smallest]]) {
smallest = 2 * i + 1;
}
if (smallest != i) {
swap(heap[i], heap[smallest]);
i = smallest;
} else {
break;
}
}
}
// Function to get the minimum element from the heap
int getMin() {
return elements[heap[1]]; // Return the true minimum
}
int main() {
ifstream fin("heapuri.in");
ofstream fout("heapuri.out");
int N;
fin >> N;
for (int i = 0; i < N; ++i) {
int operation, x;
fin >> operation;
if (operation == 1) {
// Insert operation
fin >> x;
elements[++elementCount] = x; // Store element in chronological order
insertHeap(elementCount); // Insert the index of the element into the heap
} else if (operation == 2) {
// Delete operation
fin >> x;
deleteFromHeap(x); // Remove the x-th inserted element
} else if (operation == 3) {
// Minimum query
fout << getMin() << '\n'; // Output the minimum element
}
}
fin.close();
fout.close();
return 0;
}