Pagini recente » Cod sursa (job #671237) | Cod sursa (job #1842385) | Cod sursa (job #1561927) | Cod sursa (job #704546) | Cod sursa (job #1217820)
#include<iostream>
#include<fstream>
using namespace std;
int heap[1000000];
int i;
int pos[200100];
int t[200100];
int pr=1;
class Heap
{
private:
void order_up(int position)
{
while(position!=1 && heap[position/2] > heap[position])
{
swap(heap[position],heap[position/2]);
swap(t[pos[position]],t[pos[position/2]]);
swap(pos[position],pos[position/2]);
position=position/2;
}
}
void order_down(int position)
{
int child;
do
{
if(position*2<i)
{
if((position*2+1)<i)
{
child = (heap[position*2] < heap[position*2+1]) ? position*2 : (position*2 + 1);
}
else
{
child=position*2;
}
if(heap[position]>heap[child])
{
swap(heap[position],heap[child]);
swap(t[pos[position]],t[pos[child]]);
swap(pos[position],pos[child]);
position=child;
}
else
break;
}
}while(position*2<i);
}
public:
Heap(){i=1;}
void add_to_heap(int value)
{
heap[i]=value;
pos[i]=t[pr]=i;
order_up(i++);
pr++;
}
void delete_from_heap(int id)
{
int position=t[id];
swap(heap[position],heap[i-1]);
swap(t[pos[position]],t[pos[i-1]]);
swap(pos[position],pos[i-1]);
--i;
if(position/2 >1 && heap[position/2]>heap[position])
{
order_up(position);
}
else
{
order_down(position);
}
}
int getMin()
{
return heap[1];
}
void printHeap()
{
for(int j=1;j<i;j++)
cout<<heap[j]<<" ";
cout<<endl;
}
};
void exec(const char *name_i,const char *name_o)
{
Heap heap;
ifstream f(name_i);
ofstream fo(name_o);
int lines;
f>>lines;
int operation;
for(int j=1;j<=lines;j++)
{
f>>operation;
if(operation==1)
{
int value;
f>>value;
heap.add_to_heap(value);
}else if(operation==2)
{
int elem;
f>>elem;
heap.delete_from_heap(elem);
}
else if(operation==3)
{
if(i>1)
fo<<heap.getMin()<<endl;
}
}
f.close();
fo.close();
}
int main()
{
exec("heapuri.in","heapuri.out");
return 0;
}