Pagini recente » Cod sursa (job #2608645) | Cod sursa (job #2735586) | Cod sursa (job #2213657) | Cod sursa (job #1337824) | Cod sursa (job #2512939)
#include <cstdio>
#include <algorithm>
using namespace std;
const int NMAX = 200505;
struct entry {
int value, originalPos;
bool operator < (const entry& other) const {
return value < other.value;
}
};
int ops, insertions, N, posInHeap[NMAX];
entry heap[NMAX];
void swapHeapPositions(int pos1, int pos2) {
swap(heap[pos1], heap[pos2]);
posInHeap[heap[pos1].originalPos] = pos1;
posInHeap[heap[pos2].originalPos] = pos2;
}
void moveUpIfNecessary(int pos) {
while (pos / 2 > 0 && heap[pos] < heap[pos / 2]) {
swapHeapPositions(pos, pos / 2);
pos /= 2;
}
}
void insertHeap(entry& newEntry) {
heap[++N] = newEntry;
posInHeap[newEntry.originalPos] = N;
moveUpIfNecessary(N);
}
int findBestChild(int pos) {
if (2 * pos > N) {
return -1;
}
if (2 * pos + 1 <= N && heap[2 * pos + 1] < heap[pos * 2]) {
return 2 * pos + 1;
}
return 2 * pos;
}
void moveDownIfNecessary(int pos) {
while (2 * pos <= N && heap[findBestChild(pos)] < heap[pos]) {
int bestChild = findBestChild(pos);
swapHeapPositions(pos, bestChild);
pos = bestChild;
}
}
void removeFromHeap(int pos) {
swapHeapPositions(pos, N);
N--;
moveUpIfNecessary(pos);
moveDownIfNecessary(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: {
scanf("%d", &x);
entry newEntry{x, ++insertions};
insertHeap(newEntry);
break;
}
case 2: {
scanf("%d", &x);
removeFromHeap(posInHeap[x]);
break;
}
case 3: {
printf("%d\n", heap[1].value);
break;
}
}
}
return 0;
}