Pagini recente » Cod sursa (job #863336) | Cod sursa (job #2751437) | Cod sursa (job #2005538) | Cod sursa (job #933166) | Cod sursa (job #1189279)
#include <iostream>
#include <stdio.h>
#include <vector>
#include <map>
using namespace std;
vector<int> min_heap;
vector<int> order;
map <int, int> mapHeapToCron;
int heapSize = 0;
void swapElementsInHeap(int poz1, int poz2) {
swap(min_heap[poz1], min_heap[poz2]);
int orderPoz1 = mapHeapToCron[poz1];
int orderPoz2 = mapHeapToCron[poz2];
order[orderPoz1] = poz2;
order[orderPoz2] = poz1;
mapHeapToCron[poz2] = orderPoz1;
mapHeapToCron[poz1] = orderPoz2;
}
void insertInHeap(int x) {
heapSize ++;
order.push_back(heapSize - 1);
min_heap.push_back(x);
mapHeapToCron[heapSize - 1] = heapSize - 1;
int i = heapSize - 1;
int parentI = i / 2;
while (i >= 0 && min_heap[i] < min_heap[parentI]) {
swapElementsInHeap(i, parentI);
i = parentI;
parentI = parentI / 2;
}
}
void printMin() {
cout << min_heap[0] << endl;
}
void min_heapify(int poz) {
int left = 2 * poz;
int right = 2 * poz + 1;
int smallest;
if ( left < heapSize && min_heap[left] < min_heap[poz]) {
smallest = left;
} else {
smallest = poz;
}
if (right < heapSize && min_heap[right] < min_heap[poz]) {
smallest = right;
}
if (smallest != poz) {
swapElementsInHeap(smallest, poz);
min_heapify(smallest);
}
}
void removeTheXElement(int poz) {
int nodeHeap = order[poz - 1];
int lastIndex = heapSize - 1;
swapElementsInHeap (nodeHeap, lastIndex);
heapSize --;
min_heapify(0);
}
int main() {
freopen("heapuri.in", "r", stdin);
freopen("heapuri.out", "w", stdout);
int N;
cin >> N;
for (int i = 0; i < N; i++) {
int op;
cin >> op;
if (op == 1 || op == 2) {
int x;
cin >> x;
if (op == 1) {
insertInHeap(x);
} else if (op == 2) {
removeTheXElement(x);
}
} else if (op == 3) {
printMin();
}
}
fclose(stdin);
fclose(stdout);
return 0;
}