Pagini recente » Cod sursa (job #548673) | Cod sursa (job #2853689) | Cod sursa (job #146116) | Cod sursa (job #1804924) | Cod sursa (job #1611777)
#include <stdio.h>
#define FOR(i,a,b) for(int i=a; i < b; ++i)
#define MAXN 200010
using namespace std;
int heapSize;
int heap[MAXN];
int initialPos[MAXN];
int posInHeap[MAXN];
// sztm Erzsebet
inline int parent(int x) {
return x >> 1;
}
inline int leftChild(int x) {
return x << 1;
}
inline int rightChild(int x) {
return (x << 1) + 1;
}
void swap(int x, int y) {
heap[x] ^= heap[y] ^= heap[x] ^= heap[y];
initialPos[x] ^= initialPos[y] ^= initialPos[x] ^= initialPos[y];
posInHeap[initialPos[x]] = x;
posInHeap[initialPos[y]] = y;
}
void shiftDown(int x) {
int curr = x;
while (curr <= heapSize) {
int swapWith = curr;
int left = leftChild(curr);
int right = rightChild(curr);
if (left <= heapSize && heap[left] < heap[swapWith]) swapWith = left;
if (right <= heapSize && heap[right] < heap[swapWith]) swapWith = right;
if (swapWith == curr) break;
swap(curr, swapWith);
curr = swapWith;
}
}
void shiftUp(int x) {
int curr = x;
while (parent(curr) > 0 && heap[parent(curr)] > heap[curr]) {
swap(curr, parent(curr));
curr = parent(curr);
}
}
void heapInsert(int value, int pos) {
heap[heapSize+1] = value;
initialPos[heapSize+1] = pos;
posInHeap[pos] = heapSize+1;
heapSize++;
shiftUp(heapSize);
}
void heapRemove(int pos) {
int newPos = posInHeap[pos];
swap(heapSize, newPos);
heapSize--;
if (newPos <= heapSize) {
if (newPos > 1 && heap[parent(newPos)] > heap[newPos]) {
shiftUp(newPos);
} else {
shiftDown(newPos);
}
}
}
int main() {
freopen("heapuri.in", "r", stdin);
freopen("heapuri.out", "w", stdout);
int n, i = 1;
scanf("%d", &n);
FOR(j,0,n) {
int op, x;
scanf("%d", &op);
if (op == 1) {
scanf("%d", &x);
heapInsert(x, i);
i++;
} else if (op == 2) {
scanf("%d", &x);
heapRemove(x);
} else {
printf("%d\n", heap[1]);
}
}
return 0;
}