Pagini recente » Monitorul de evaluare | Cod sursa (job #189843) | Cod sursa (job #702982) | Rating marian darius (dariusmarian) | Cod sursa (job #1503463)
#include <stdio.h>
struct heap {
int tree[200000];
int insertrank[200000];
int insertno;
int end;
} heap;
void swap(int *a, int *b)
{
int aux = *a;
*a = *b;
*b = aux;
}
void heap_add(int newitem)
{
int itempos = ++heap.end;
heap.insertrank[itempos] = ++heap.insertno;
heap.tree[itempos] = newitem;
int parent = (itempos - 1) / 2;
int aux = 1;
while (aux) {
aux = 0;
if (heap.tree[itempos] < heap.tree[parent]) {
swap(&heap.tree[itempos], &heap.tree[parent]);
swap(&heap.insertrank[itempos], &heap.insertrank[parent]);
itempos = parent;
parent = (itempos - 1) / 2;
aux = 1;
}
}
}
void heap_del(int insitmno)
{
int itempos, i;
for (i = 0; i <= heap.end; ++i) {
if (insitmno == heap.insertrank[i]) {
itempos = i;
}
}
heap.tree[itempos] = heap.tree[heap.end];
heap.insertrank[itempos] = heap.insertrank[heap.end--];
int aux = 1, smallest;
while (aux) {
aux = 0;
smallest = 2 * itempos + 1;
if (smallest < heap.end) {
smallest = heap.tree[smallest] < heap.tree[smallest + 1] ? smallest : smallest + 1;
} else if (smallest > heap.end) {
smallest = 0;
}
if (heap.tree[smallest] < heap.tree[itempos] && smallest) {
swap(&heap.tree[itempos], &heap.tree[smallest]);
swap(&heap.insertrank[itempos], &heap.insertrank[smallest]);
itempos = smallest;
aux = 1;
}
}
}
int main(void)
{
heap.end = heap.insertno = -1;
int N;
FILE *in = fopen("heapuri.in", "r");
FILE *out = fopen("heapuri.out", "w");
fscanf(in, "%d", &N);
int i, op, aux;
for (i = 0; i < N; ++i) {
fscanf(in, "%d", &op);
switch (op) {
case 1:
fscanf(in, "%d", &aux);
heap_add(aux);
break;
case 2:
fscanf(in, "%d", &aux);
heap_del(aux - 1);
break;
case 3:
fprintf(out, "%d\n", heap.tree[0]);
break;
}
}
fclose(in);
fclose(out);
return 0;
}