Pagini recente » Cod sursa (job #1771939) | Cod sursa (job #885453) | Cod sursa (job #932118) | Cod sursa (job #768372) | Cod sursa (job #1754179)
#include<bits/stdc++.h>
#define NMAX 200001
#define swapp(x, y) { int tmp = x; x = y; y = tmp; }
using namespace std;
int N, operation, element, heap[NMAX], iHeapPz[NMAX], heapPz[NMAX], counter = 0;
void heapInsert(int nrcrt, int element) {
heap[++heap[0]] = element;
iHeapPz[heap[0]] = nrcrt;
int position = heapPz[nrcrt] = heap[0];
while(position / 2 >= 1 && heap[position / 2] > element) {
swapp(heap[position / 2], heap[position]);
swapp(iHeapPz[position / 2], iHeapPz[position]);
heapPz[nrcrt] = position / 2;
heapPz[iHeapPz[position]] = position;
position >>= 1;
}
}
void heapDelete(int nrcrt) {
if (heap[0] == 1) {
--heap[0];
return;
}
swapp(heap[heapPz[nrcrt]], heap[heap[0]]);
iHeapPz[heapPz[nrcrt]] = iHeapPz[heap[0]];
heapPz[iHeapPz[heap[0]]] = heapPz[nrcrt];
--heap[0];
int position = heapPz[nrcrt], newPosition = -1;
while(true) {
int left = position * 2, right = left + 1;
newPosition = position;
if (left <= heap[0] && heap[left] < heap[newPosition]) newPosition = left;
if (right <= heap[0] && heap[right] < heap[newPosition]) newPosition = right;
if (position != newPosition) {
swapp(heap[newPosition], heap[position]);
swapp(iHeapPz[newPosition], iHeapPz[position]);
heapPz[iHeapPz[newPosition]] = newPosition;
heapPz[iHeapPz[position]] = position;
} else break;
}
}
int main() {
freopen("heapuri.in", "r", stdin);
freopen("heapuri.out", "w", stdout);
scanf("%d", &N);
for (int it = 1; it <= N; ++it) {
scanf("%d", &operation);
switch(operation) {
case 1:
++counter;
scanf("%d", &element);
heapInsert(counter, element);
break;
case 2:
scanf("%d", &element);
heapDelete(element);
break;
case 3:
printf("%d\n", heap[1]);
break;
}
}
return 0;
}