Pagini recente » Cod sursa (job #1155440) | Cod sursa (job #1613466) | Cod sursa (job #3332339) | Cod sursa (job #2925737) | Cod sursa (job #3309223)
#include <bits/stdc++.h>
using namespace std;
struct date {
int val, ind; ///valoarea si indicele cronologic
} heap[200005];
int pozHeap[200005]; ///nodul in din heap in care se afla o valoare, in fuctie de indicele cronologic
int fiu_stanga(int x) {
return 2*x;
}
int fiu_dreapta(int x) {
return 2*x+1;
}
int parent(int nod) {
return nod/2;
}
void swapNodes(int nod1, int nod2) {
swap(heap[nod1], heap[nod2]);
swap(pozHeap[heap[nod1].ind], pozHeap[heap[nod2].ind]);
}
void comparSus(int nodPoz) {
while(nodPoz>1 && heap[nodPoz].val<heap[parent(nodPoz)].val)
{
swapNodes(nodPoz, parent(nodPoz));
nodPoz=parent(nodPoz);
}
}
void comparJos(int nodPoz, int heapSize) {
int fiu=0;
if(fiu_stanga(nodPoz)<=heapSize)
{
fiu=fiu_stanga(nodPoz);
if(fiu_dreapta(nodPoz)<=heapSize && heap[fiu_dreapta(nodPoz)].val<heap[fiu_stanga(nodPoz)].val)
fiu=fiu_dreapta(nodPoz);
}
if(!fiu)
return;
if(heap[fiu].val<heap[nodPoz].val)
{
swapNodes(fiu, nodPoz);
comparJos(fiu, heapSize);
}
}
void insertNod(int valoare, int indice, int &heapSize)
{
heapSize+=1;
heap[heapSize]={valoare, indice};
pozHeap[indice]=heapSize;
comparSus(heapSize);
}
void deleteNod(int indice, int &heapSize)
{
int pozNod=pozHeap[indice];
swapNodes(pozNod, heapSize);
heapSize--;
comparSus(pozNod);
comparJos(pozNod, heapSize);
}
int main()
{
ifstream cin("heapuri.in");
ofstream cout("heapuri.out");
ios::sync_with_stdio(false);
cin.tie(NULL);
int q, type, x, cnt=0, heapSize=0;
cin>>q;
while(q--)
{
cin>>type;
if(type==1)
{
cin>>x;
cnt++;
insertNod(x, cnt, heapSize);
}
else if(type==2)
{
cin>>x;
deleteNod(x, heapSize);
}
else
{
cout<<heap[1].val<<'\n';
}
}
return 0;
}