Pagini recente » Cod sursa (job #1297954) | Cod sursa (job #1838566) | Cod sursa (job #1668638) | Cod sursa (job #2756860) | Cod sursa (job #472671)
Cod sursa(job #472671)
#include<fstream>
using namespace std;
#define nm 200002
ifstream f("heapuri.in");
ofstream g("heapuri.out");
int heap[nm],on[nm],poz[nm],el[nm];
int op,x,n,k=1,dim;
inline int father(int k) { return k/2; }
inline int left_son(int k) { return k*2; }
inline int right_son(int k) { return k*2+1; }
void percolate(int N, int k)
{ int key=heap[k];
while(k>1 && key<heap[father(k)])
{ heap[k]=heap[father(k)];
swap(poz[el[k]],poz[el[father(k)]]);
swap(el[k],el[father(k)]);
k=father(k);
}
heap[k]=key;
}
void sift(int N, int k)
{ int son=0;
do
{ son=0;
if(left_son(k)<=N)
{ son=left_son(k);
if(right_son(k)<=N && heap[right_son(k)]<heap[k])
son=right_son(k);
if(heap[son]>heap[k])
son=0;
}
if(son)
{ swap(heap[k],heap[son]);
swap(poz[el[k]],poz[el[son]]);
swap(el[k],el[son]);
k=son;
}
}while(son);
}
void insert(int val)
{ heap[dim++]=val;
percolate(dim-1,dim-1);
}
void erase(int val)
{ int pos=poz[val];
heap[pos]=heap[dim-1];
poz[el[dim-1]]=pos;
el[pos]=el[dim-1];
dim--;
if(pos>1 && heap[pos]<heap[father(pos)])
percolate(dim-1,pos);
else
sift(dim-1,pos);
}
int main()
{ f>>n;
dim=1;
for(int i=1;i<=n;i++)
{ f>>op;
if(op==1)
{ f>>x;
on[k++]=x;
el[dim]=k-1;
poz[k-1]=dim;
insert(x);
}
else
if(op==2)
{ f>>x;
erase(x);
on[x]=-1;
}
else
g<<heap[1]<<'\n';
}
f.close();
g.close();
return 0;
}