Pagini recente » Cod sursa (job #90964) | Cod sursa (job #2096532) | Cod sursa (job #2443029) | Cod sursa (job #2476450) | Cod sursa (job #2955398)
#include <fstream>
const int NMAX=200005;
using namespace std;
ifstream fin("heapuri.in");
ofstream fout("heapuri.out");
struct nod
{
int cron, val;
}h[NMAX];
void creare(nod [], int&);
void inserare(nod [], int&, int, int);
void combinare(nod [], int&, int);
void sterge(nod [], int&, int);
int n;
int pz[NMAX]; //pozitia pe care se afla in heap al x-lea element citit
int main()
{
ios_base::sync_with_stdio(false);
creare(h, n);
return 0;
}
void inserare(nod h[], int& n, int x, int i)
{
int poz=n+1, tpoz=poz/2;
while(tpoz>0 && h[tpoz].val>x)
{
h[poz]=h[tpoz];
pz[h[poz].cron]=poz;
poz=tpoz;
tpoz=poz/2;
}
h[poz]={i, x};
pz[i]=poz;
n++;
}
void sterge(nod h[], int& n, int x)
{
h[pz[x]]=h[n--];
combinare(h, n, pz[x]);
}
void combinare(nod h[], int& n, int i)
{
//combin heapurile corecte cu radacinile 2i si 2i+1 cu nodul i
int x=h[i].val, xp=h[i].cron, tata=i, fiu=2*i, bunic=i/2;
//ma asigur ca heapul are structura de heap
while(bunic!=0 && h[bunic].val>x)
{
h[tata]=h[bunic];
pz[h[tata].cron]=tata;
tata=bunic;
bunic=tata/2;
}
while(fiu<=n)
{
//daca exista fiu drept si e mai mic
if(fiu+1<=n && h[fiu+1].val<h[fiu].val) fiu++;
if(h[fiu].val<x)
{
h[tata]=h[fiu];
pz[h[tata].cron]=tata;
tata=fiu;
fiu=fiu*2;
}
else break;
}
h[tata]={xp, x};
pz[xp]=tata;
}
void creare(nod h[], int& n)
{
int i, q, x, op, nr=0;
fin>>q; n=0;
for(i=1; i<=q; i++)
{
fin>>op;
if(op==1)
{
fin>>x; nr++;
inserare(h, n, x, nr);
}
else if(op==2)
{
fin>>x;
sterge(h, n, x);
}
else fout<<h[1].val<<'\n';
}
}