Pagini recente » Cod sursa (job #1132947) | Cod sursa (job #1644203) | Cod sursa (job #2207526) | Cod sursa (job #1550696) | Cod sursa (job #2835995)
#include <fstream>
std::ifstream in("heapuri.in");
std::ofstream out("heapuri.out");
constexpr int N = 2e5+1;
int heap[N], v[N], valPos[N], nh, n;
void swapEl(int pos1, int pos2){
std::swap(heap[pos1], heap[pos2]);
valPos[heap[pos1]] = pos1;
valPos[heap[pos2]] = pos2;
}
void goUp(int pos){
while(pos > 1 && v[heap[pos]] < v[heap[pos/2]]){
swapEl(pos, pos/2);
pos /= 2;
}
}
void goDown(int pos){
int rChild = pos * 2, lChild = rChild + 1, parent = pos;
if(rChild <= nh && v[heap[rChild]] < v[heap[parent]]){
parent = rChild;
}
if(lChild <= nh && v[heap[lChild]] < v[heap[parent]]){
parent = lChild;
}
if(parent != pos){
swapEl(parent, pos);
goDown(parent);
}
}
void add(int val){
heap[++nh] = val;
valPos[val] = nh;
goUp(nh);
}
void remove(int pos){
if(pos == nh){
--nh;
return;
}
swapEl(nh, pos);
--nh;
goUp(pos);
goDown(pos);
}
int main(){
int nrOp;
in >> nrOp;
for(int i=0; i<nrOp; ++i){
int type;
in >> type;
switch(type){
case 1:
in >> v[++n];
add(n);
break;
case 2:
int idx;
in >> idx;
remove(valPos[idx]);
break;
default:
out << v[heap[1]] << '\n';
}
}
}