Pagini recente » Cod sursa (job #636911) | Cod sursa (job #1764605) | Cod sursa (job #591795) | Cod sursa (job #872627) | Cod sursa (job #504213)
Cod sursa(job #504213)
#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)
{
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 insert(int element)
{
h[++currentSize].value = element;
h[currentSize].orderIndex = currentSize;
totalInsert++;
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;
}