Pagini recente » Cod sursa (job #1960480) | Cod sursa (job #3221165) | Cod sursa (job #2715335) | Cod sursa (job #316378) | Cod sursa (job #1217922)
#include<cstdio>
using namespace std;
int heap[1000000];
int i=1;
int pos[200100];
int t[200100];
int pr=1;
void swapHeap(int t1,int t2)
{
int aux=heap[t1];
heap[t1]=heap[t2];
heap[t2]=aux;
aux=t[pos[t1]];
t[pos[t1]]=t[pos[t2]];
t[pos[t2]]=aux;
aux=pos[t1];
pos[t1]=pos[t2];
pos[t2]=aux;
}
void order_up(int position)
{
while(position/2 && heap[position/2] > heap[position])
{
swapHeap(position,position/2);
position=position/2;
}
}
void order_down(int position)
{
int child;
while(position*2<i)
{
if((position*2+1)<i)
{
if(heap[position*2] < heap[position*2+1])
child=position*2;
else
child=position*2 +1;
}
else
{
child=position*2;
}
if(heap[position]>heap[child])
{
swapHeap(position,child);
position=child;
}
else
break;
}
}
void add_to_heap(int value)
{
heap[i]=value;
pos[i]=pr;
t[pr]=i;
order_up(i++);
++pr;
}
void delete_from_heap(int id)
{
int position=t[id];
swapHeap(position,i-1);
--i;
if(position/2 && heap[position/2]>heap[position])
{
order_up(position);
}
else
{
order_down(position);
}
}
void exec(const char *name_i,const char *name_o)
{
FILE *fin;
fin=fopen(name_i,"r");
FILE *fon;
fon=fopen(name_o,"w");
int lines;
fscanf(fin,"%d",&lines);
int operation;
for(int j=1;j<=lines;j++)
{
fscanf(fin,"%d",&operation);
if(operation==1)
{
int value;
fscanf(fin,"%d",&value);
add_to_heap(value);
}else if(operation==2)
{
int elem;
fscanf(fin,"%d",&elem);
delete_from_heap(elem);
}
else if(operation==3)
{
if(i>1)
fprintf(fon,"%d\n",heap[1]);
}
}
fclose(fin);
fclose(fon);
}
int main()
{
exec("heapuri.in","heapuri.out");
return 0;
}