Pagini recente » Cod sursa (job #2829352) | Rating cocos florin (cocosflorin) | Cod sursa (job #1732750) | Cod sursa (job #954024) | Cod sursa (job #1189400)
#include <iostream>
#include <stdio.h>
#include <vector>
#include <map>
using namespace std;
#define MAXN 200003
int min_heap[MAXN];
int order[MAXN];
map <int, int> mapHeapToCron;
int heapSize = -1;
int L = -1;
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++;
min_heap[heapSize] = x;
L++;
order[L] = heapSize;
mapHeapToCron[heapSize] = L;
int i = heapSize;
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;
swapElementsInHeap (nodeHeap, lastIndex);
heapSize --;
//order.pop_back();
mapHeapToCron.erase(lastIndex);
// min_heap.erase(min_heap.begin() + lastIndex);
min_heapify(nodeHeap);
}
int main() {
freopen("heapuri.in", "r", stdin);
freopen("heapuri.out", "w", stdout);
int N;
cin >> N;
mapHeapToCron.clear();
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;
}