Pagini recente » Cod sursa (job #3288701) | Cod sursa (job #242204) | Cod sursa (job #1992593) | Cod sursa (job #1405857) | Cod sursa (job #3129866)
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
ifstream f("heapuri.in");
ofstream g("heapuri.out");
class MinHeap{
private:
vector<int> heap;
vector<int> pos;
public:
MinHeap(){
heap = {};
pos = {};
}
// void print(){
// for(auto i=0;i<heap.size();++i)
// cout<<heap[i];
// }
void repairHeapDown(int poz){
if (2*poz+1 >= static_cast<int>(heap.size())){
return;
}
if (2*poz+2 == static_cast<int>(heap.size()) || heap[2*poz+1] > heap[2*poz+2]){
if(heap[2*poz+1] < heap[poz]){
swap(heap[2*poz+1], heap[poz]);
repairHeapDown(2*poz+1);
return;
}
else return;
}
else{
if(heap[2*poz+2] < heap[poz]){
swap(heap[2*poz+2], heap[poz]);
repairHeapDown(2*poz+2);
return;
}
else return;
}
}
void repairHeapUp(int poz){
while(poz){
int dad = (poz-1)/2;
if (heap[dad] > heap[poz]){
swap(heap[dad],heap[poz]);
poz = dad;
}
else break;
}
}
// insert element x
void insert(int x){
heap.push_back(x);
pos.push_back(x);
repairHeapUp(heap.size()-1);
}
// delete the element that was the i-th inserted
void del(int i){
//find the element that was the i-th inserted
int el = pos[i-1];
// find the index of el in heap
for(auto j = 0; j < heap.size(); ++j)
if (heap[j] == el){
i = j;
break;
}
// delete the element at index i from the heap
heap[i] = heap[heap.size()-1];
heap.pop_back();
repairHeapDown(i);
repairHeapUp(i);
}
// print minimum element
void mini(){
g<<heap.front()<<endl;
}
};
int main(){
MinHeap H;
int n, a, b;
f>>n;
for(int i = 0; i < n; ++i){
f>>a;
switch(a){
case 1:{
f>>b;
H.insert(b);
break;
}
case 2:{
f>>b;
H.del(b);
break;
}
case 3:{
H.mini();
break;
}
default:{
break;
}
}
}
f.close();
g.close();
return 0;
}