Pagini recente » Cod sursa (job #2431814) | Cod sursa (job #1176753) | Ciorna | Atasamentele paginii Clasament tema_vacanta_sambata_14.30 | Cod sursa (job #2436514)
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
ifstream fin("heapuri.in");
ofstream fout("heapuri.out");
int heap[200010];
vector<int> heapOrder;
int heapSize = 0;
void swim(int x)
{
while(x!=0&&heap[(x-1)/2]>heap[x])
{
swap(heap[(x-1)/2],heap[x]);
x=(x-1)/2;
}
}
void sink(int x)
{
while((2*x+1)<heapSize)
{
int smallestChildIndex = 2*x+1;
if((2*x+2)<heapSize && heap[2*x+2]<heap[smallestChildIndex])
{
smallestChildIndex = 2*x+2;
}
if(heap[smallestChildIndex]>heap[x])
return;
else
{
swap(heap[smallestChildIndex],heap[x]);
}
x = smallestChildIndex;
}
}
void add(int x)
{
heapOrder.push_back(x);
heapSize++;
heap[heapSize-1]=x;
swim(x);
}
void del(int pos)
{
int val = heapOrder[pos-1];
int i;
for(i=0;i<heapSize;i++)
{
if(heap[i]==val)
break;
}
swap(heap[i],heap[heapSize-1]);
heapSize--;
if(i!=0)
{
if(heap[(i-1)/2]>heap[i])
swim(i);
else
sink(i);
}
else
sink(i);
}
int peek()
{
return heap[0];
}
int main()
{
int q,t,x;
fin>>q;
while(q--)
{
fin>>t;
if(t==1)
{
fin>>x;
add(x);
}
else if(t==2)
{
fin>>x;
del(x);
}
else{
fout<<peek()<<'\n';
}
}
return 0;
}