Pagini recente » Cod sursa (job #2397151) | Cod sursa (job #2872148) | Cod sursa (job #2183289) | Cod sursa (job #2491235) | Cod sursa (job #516427)
Cod sursa(job #516427)
#include <fstream>
#include <algorithm>
using namespace std;
int a[200005],heap[200005],poz[200005],h,n;
int adauga(int i,int key)
{
while(i>1 and a[heap[i/2]]>a[key])
{
heap[i]=heap[i/2];
poz[i/2]=i;
i=i/2;
}
heap[i]=key;
poz[key]=i;
}
void heapify(int i)
{
int left,right,smallest;
left=2*i;
right=2*i+1;
smallest=i;
if(left<=h and a[heap[left]]<a[heap[i]]) smallest=left;
if(right<=h and a[heap[right]]<a[heap[smallest]]) smallest=right;
if(smallest!=i) {
swap(poz[heap[i]],poz[heap[smallest]]);
swap(heap[i],heap[smallest]);
heapify(smallest);
}
}
int main()
{
int tip,t,x;
ifstream fi("heapuri.in");
ofstream fo("heapuri.out");
fi>>t;
while(t--)
{
fi>>tip;
if(tip<3) fi>>x;
if(tip==1) //adauga in heap element x
{
a[++n]=x;
heap[++h]=n;
adauga(h,n);
}
if(tip==2) //sterge al x-lea element din heap
{
swap(heap[poz[x]],heap[h]);
h--;
heapify(poz[x]);
}
if(tip==3) fo<<a[heap[1]]<<"\n";
}
return 0;
}