Pagini recente » Cod sursa (job #780369) | Cod sursa (job #408172) | Cod sursa (job #1842437) | Cod sursa (job #1383317) | Cod sursa (job #2830113)
#include <stdio.h>
#include <algorithm>
using namespace std;
#define MAXN 200000
struct heaps{
int nr, pos;
bool exist;
};
heaps heap[MAXN];
int v[MAXN];
int heap_size;
int parent(int n) {
return (n - 1) / 2;
}
int left_child(int n) {
return n * 2 + 1;
}
int right_child(int n) {
return n * 2 + 2;
}
void upheap(int loc_in_heap) {
while ( loc_in_heap > 0 && heap[parent(loc_in_heap)].nr > heap[loc_in_heap].nr ) {
swap(v[heap[parent(loc_in_heap)].pos], v[heap[loc_in_heap].pos]);
swap(heap[parent(loc_in_heap)], heap[loc_in_heap]);
loc_in_heap = parent(loc_in_heap);
}
}
void downheap(int loc_in_heap) {
int minim;
minim = loc_in_heap;
if ( left_child(loc_in_heap) < heap_size && heap[left_child(loc_in_heap)].nr < heap[minim].nr ) {
minim = left_child(loc_in_heap);
}
if ( right_child(loc_in_heap) < heap_size && heap[right_child(loc_in_heap)].nr < heap[minim].nr ) {
minim = right_child(loc_in_heap);
}
if ( minim != loc_in_heap ) {
swap(v[heap[minim].pos], v[heap[loc_in_heap].pos]);
swap(heap[minim], heap[loc_in_heap]);
downheap(minim);
}
}
void erase_min() {
heap_size--;
swap(v[heap[0].pos], v[heap[heap_size].pos]);
swap(heap[0], heap[heap_size]);
downheap(0);
}
int get_min() {
return heap[0].nr;
}
int main() {
FILE *fin, *fout;
fin = fopen("heapuri.in", "r");
fout = fopen("heapuri.out", "w");
int n, i, q, nr, pos_elem, i2;
fscanf(fin, "%d", &n);
heap_size = i2 = 0;
for ( i = 0; i < n; i++ ) {
fscanf(fin, "%d", &q);
if ( q == 1 ) {
fscanf(fin, "%d", &nr);
heap[heap_size].nr = nr;
heap[heap_size].pos = i2;
heap[heap_size].exist = true;
v[i2] = heap_size;
upheap(heap_size);
heap_size++;
i2++;
} else if ( q == 2 ) {
fscanf(fin, "%d", &nr);
nr--;
pos_elem = v[nr];
heap[pos_elem].exist = false;
} else if ( q == 3 ) {
while ( !heap[0].exist ) {
erase_min();
}
fprintf(fout, "%d\n", get_min());
}
}
fclose(fin);
fclose(fout);
return 0;
}