Pagini recente » Cod sursa (job #589278) | Cod sursa (job #2039505) | Cod sursa (job #650224) | Cod sursa (job #952393) | Cod sursa (job #472377)
Cod sursa(job #472377)
#include<fstream>
using namespace std;
#define nm 200002
ifstream f("heapuri.in");
ofstream g("heapuri.out");
int heap[nm],on[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)];
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]);
k=son;
}
}while(son);
}
int search(int val,int k, int N)
{ int son;
if(left_son(k)<=N)
{ son=left_son(k);
if(heap[son]==val)
return son;
else
{ if(heap[son]>val)
search(val,right_son(k),N);
else
if(heap[right_son(k)]>val)
search(val,left_son(k),N);
else
{ search(val,left_son(k),N);
search(val,right_son(k),N);
}
}
}
}
void insert(int val)
{ heap[dim++]=val;
percolate(dim-1,dim-1);
}
void erase(int val)
{ if(heap[1]==val)
{ heap[1]=heap[dim-1];
dim--;
for(int i=(dim-1)/2;i>0;i--)
sift(dim-1,i);
}
else
{ int poz=search(val,1,dim);
heap[poz]=heap[dim-1];
dim--;
if(poz>1 && heap[poz]<heap[father(poz)])
percolate(dim-1,poz);
else
sift(dim-1,poz);
}
}
int main()
{ f>>n;
dim=1;
for(int i=1;i<=n;i++)
{ f>>op;
if(op==1)
{ f>>x;
on[k++]=x;
insert(x);
}
else
if(op==2)
{ f>>x;
erase(on[x]);
on[x]=-1;
}
else
g<<heap[1]<<'\n';
}
f.close();
g.close();
return 0;
}