Pagini recente » Cod sursa (job #3194606) | Cod sursa (job #3273068) | Cod sursa (job #2744521) | Cod sursa (job #2360447) | Cod sursa (job #504210)
Cod sursa(job #504210)
#include <stdio.h>
#define file_in "heapuri.in"
#define file_out "heapuri.out"
#define MAX 200001
typedef struct heap {
int value;
int orderIndex;
} Heap;
Heap h[MAX];
int order[MAX], currentSize, totalInsert;
int father(int position)
{
return position/2;
}
int leftSon(int position)
{
return position*2;
}
int rightSon(int position)
{
return position*2+1;
}
int min()
{
return h[1].value;
}
void swap( Heap *h1, Heap *h2, int position)
{
int v = (*h1).value;
int oi = (*h1).orderIndex;
order[ h[position].orderIndex ] = father(position);
Heap temp = *h1;
*h1 = *h2;
*h2 = temp;
order[ h[position].orderIndex ] = position;
}
void up(int position)
{
while( h[father(position)].value > h[position].value )
{
swap( &h[position], &h[father(position)], position );
position = father(position);
}
}
void down(int p)
{
int min = 0;
while(1)
{
if( leftSon(p) <= currentSize )
{
min = leftSon(p);
if( rightSon(p) <= currentSize && h[min].value > h[rightSon(p)].value )
min = rightSon(p);
if( h[p].value > h[min].value )
swap( &h[min], &h[p], p);
p = min;
}
else break;
}
}
void delete(int which)
{
h[order[which]] = h[currentSize--];
down(order[which]);
}
void printHeap()
{
int i;
for(i = 1; i <= currentSize; i++)
printf("%d:%d ; ", h[i].value, h[i].orderIndex);
printf("\n");
for(i = 1; i <= totalInsert; i++)
printf("%d ", order[i]);
printf("\n");
}
void insert(int element)
{
h[++currentSize].value = element;
h[currentSize].orderIndex = currentSize;
order[totalInsert] = ++totalInsert;
up(currentSize);
}
int main()
{
FILE *in = fopen(file_in, "r");
FILE *out = fopen(file_out, "w");
int n, op, e;
fscanf(in, "%d", &n);
while(n--)
{
fscanf(in, "%d", &op);
if( op == 1 )
{
fscanf(in, "%d", &e);
insert(e);
}
else if( op == 2 )
{
fscanf(in, "%d", &e);
delete(e);
}
else if( op == 3 )
fprintf(out,"%d\n", min());
}
fclose(in);
fclose(out);
return 0;
}