Pagini recente » Cod sursa (job #2633491) | Cod sursa (job #1186899) | Cod sursa (job #1301824) | Cod sursa (job #3129730) | Cod sursa (job #1399863)
#include <fstream>
#define fiu_st(x) 2*x
#define fiu_dr(x) 2*x+1
#define tata(x) x/2
using namespace std;
ifstream f("heapuri.in");
ofstream g("heapuri.out");
const int nmax=200005;
int n,m,t,q,x,p; // n means heapsize , and m means the size of the initial array
int heap[nmax],a[nmax],poz[nmax]; // in heap vom tine indicii din vectorul initial
void swap (int x,int y)
{
int aux;
poz[heap[x]]=y;
poz[heap[y]]=x;
aux=heap[x];
heap[x]=heap[y];
heap[y]=aux;
}
void sus (int nod)
{
while (nod>1 && tata(a[heap[nod]])>a[heap[nod]])
{
swap(nod,tata(nod));
nod=tata(nod);
}
}
void jos (int nod)
{
int ok=1,fiu; // interschimbam cu fiul minim
while (ok && fiu_st(nod)<=n)
{
ok=0;
fiu=fiu_st(nod);
if (fiu_dr(nod)<=n && a[heap[fiu_dr(nod)]]<a[heap[fiu_st(nod)]])
fiu=fiu_dr(nod);
if (a[heap[nod]]>a[heap[fiu]])
{
ok=1;
swap(nod,fiu);
nod=fiu;
}
}
}
int main()
{
f>>t;
while (t--)
{
f>>q;
if (q==1)
{
f>>x;
n++; // crestem heapul
m++; // creste vectorul
a[m]=x;
heap[n]=m;
poz[m]=n;
sus(n);
}
if (q==2)
{
f>>x;
p=poz[x];
swap(p,n);
n--;
if ((p > 1) && (a[heap[tata(p)]] > a[heap[p]]))
{
sus(p);
}
else
{
jos(p);
}
}
if (q==3)
g<<a[heap[1]]<<'\n';
}
return 0;
}