Pagini recente » Cod sursa (job #2190482) | Cod sursa (job #2251825) | Cod sursa (job #2276419) | Cod sursa (job #1555097) | Cod sursa (job #2374403)
#include <stdio.h>
#include <stdlib.h>
int whichone(int a, int b)
{
if (a < b)
return 1;
return 2;
}
void reorderHeapAdd(int **heap, int index)
{
if (index == 0)
return;
if ((*heap)[(index-1)/2] > (*heap)[index]){
int aux = (*heap)[(index-1)/2];
(*heap)[(index-1)/2] = (*heap)[index];
(*heap)[index] = aux;
reorderHeapAdd(heap, (index-1)/2);
}
}
void addToHeap(int **heap, int *numbers_in_heap, int number)
{
if (*heap == NULL)
{
*heap = (int*) calloc(1, sizeof(int));
*numbers_in_heap = 1;
(*heap)[0] = number;
}
else
{
(*numbers_in_heap)++;
*heap = (int*) realloc(*heap, *numbers_in_heap * sizeof(int));
(*heap)[*numbers_in_heap-1] = number;
reorderHeapAdd(heap,(*numbers_in_heap)-1);
}
}
void reorderHeapRemove(int **heap, int index, int numbers_in_heap)
{
if (2 * index + 1 > numbers_in_heap - 1)
return;
if (2 * index + 2 > numbers_in_heap - 1)
{
if ((*heap)[2 * index + 1] < (*heap)[index])
{
int aux = (*heap)[2 * index + 1];
(*heap)[2 * index + 1] = (*heap)[index];
(*heap)[index] = aux;
}
return;
}
else
{
if ( whichone((*heap)[2 * index + 1], (*heap)[2 *index +2]) == 1 )
{
if ((*heap)[2 * index + 1] < (*heap)[index])
{
int aux = (*heap)[2 * index + 1];
(*heap)[2 * index + 1] = (*heap)[index];
(*heap)[index] = aux;
reorderHeapRemove (heap, 2 * index + 1, numbers_in_heap);
}
}
else
{
if ((*heap)[2 * index + 2] < (*heap)[index])
{
int aux = (*heap)[2 * index + 2];
(*heap)[2 * index + 2] = (*heap)[index];
(*heap)[index] = aux;
reorderHeapRemove (heap, 2 * index + 2, numbers_in_heap);
}
}
}
}
void removeFromHeap(int **heap, int *numbers_in_heap, int number)
{
if((*numbers_in_heap)==1 && (*heap)[0]==number)
{
free(*heap);
}
else
{
for (int i=0; i < *numbers_in_heap; i++)
{
if ((*heap)[i] == number)
{
(*heap)[i] = (*heap)[*numbers_in_heap - 1];
(*heap)[*numbers_in_heap - 1] = 0;
(*numbers_in_heap)--;
(*heap) = (int*) realloc((*heap), (*numbers_in_heap) * sizeof(int));
reorderHeapRemove(heap, i, *numbers_in_heap);
break;
}
}
}
}
int main()
{
FILE *read = fopen("heapuri.in", "r");
FILE *write = fopen("heapuri.out", "w");
int *heap = NULL;
int numbers_in_heap = 0;
int n;
fscanf(read, "%d", &n);
int *cronos = calloc(n, sizeof(int));
int cronoscounter = 0;
int comanda, numar;
int ok = 0;
int i = 0;
while (i < n)
{
if (ok == 0)
fscanf(read, "%d%d", &comanda, &numar);
else
{
fscanf(read, "%d", &numar);
ok = 0;
}
if (comanda == 1)
{
addToHeap(&heap, &numbers_in_heap, numar);
cronoscounter++;
cronos[cronoscounter] = numar;
i++;
}
else if(comanda == 2)
{
removeFromHeap(&heap, &numbers_in_heap, cronos[numar]);
i++;
}
else if(comanda == 3)
{
fprintf(write, "%d\n", heap[0]);
comanda = numar;
i++;
ok = 1;
}
}
if (numbers_in_heap != 0)
free(heap);
free(cronos);
fclose(read);
fclose(write);
return 0;
}