Pagini recente » Cod sursa (job #2508146) | Cod sursa (job #2394415) | Cod sursa (job #905947) | Cod sursa (job #3233197) | Cod sursa (job #2512903)
#include <cstdio>
#include <algorithm>
using namespace std;
const int NMAX = 200505;
int ops, N, totalInsertions;
struct heapElement {
int value, originalPos;
bool operator < (const heapElement& other) {
return value < other.value;
}
};
heapElement heap[NMAX];
int entryToPos[NMAX];
void swapPositionsInHeap(int pos1, int pos2) {
swap(heap[pos1], heap[pos2]);
entryToPos[heap[pos1].originalPos] = pos1;
entryToPos[heap[pos2].originalPos] = pos2;
}
void goUpIfNecessary(int pos) {
while (pos / 2 > 0 && heap[pos] < heap[pos / 2]) {
swapPositionsInHeap(pos, pos / 2);
pos /= 2;
}
}
int getMinimumChild(int pos) {
if (pos * 2 + 1 <= N && heap[pos * 2 + 1] < heap[pos * 2]) {
return pos * 2 + 1;
}
return pos * 2;
}
void goDownIfNecessary(int pos) {
while (pos * 2 <= N && heap[getMinimumChild(pos)] < heap[pos]) {
int bestChildIdx = getMinimumChild(pos);
swapPositionsInHeap(pos, bestChildIdx);
pos = bestChildIdx;
}
}
void insertHeap(heapElement& newElement) {
heap[++N] = newElement;
entryToPos[newElement.originalPos] = N;
goUpIfNecessary(N);
}
void deleteElementOnPos(int pos) {
swapPositionsInHeap(pos, N);
N--;
goUpIfNecessary(pos);
goDownIfNecessary(pos);
}
int main() {
freopen("heapuri.in", "r", stdin);
freopen("heapuri.out", "w", stdout);
scanf("%d", &ops);
int opType, x;
for (int op = 0; op < ops; op++) {
scanf("%d", &opType);
switch(opType) {
case 1: {
heapElement newElement;
scanf("%d", &newElement.value);
newElement.originalPos = ++totalInsertions;
insertHeap(newElement);
break;
}
case 2: {
scanf("%d", &x);
deleteElementOnPos(entryToPos[x]);
break;
}
case 3: {
printf("%d\n", heap[1].value);
break;
}
}
}
return 0;
}