Pagini recente » Cod sursa (job #1050697) | Cod sursa (job #442975) | Cod sursa (job #1085325) | Cod sursa (job #776112) | Cod sursa (job #3129872)
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
ifstream f("heapuri.in");
ofstream g("heapuri.out");
class MinHeap{
private:
int cnt = 0;
vector<pair<int, int>> heap;
public:
MinHeap(){
heap = {};
}
void print(){
for(vector<int>::size_type i = 0;i<heap.size();++i)
cout<<heap[i].first<<" "<<heap[i].second<<endl;
}
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].first < heap[2*poz+2].first){
if(heap[2*poz+1].first < heap[poz].first){
swap(heap[2*poz+1], heap[poz]);
repairHeapDown(2*poz+1);
return;
}
else return;
}
else{
if(heap[2*poz+2].first < heap[poz].first){
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].first > heap[poz].first){
swap(heap[dad],heap[poz]);
poz = dad;
}
else break;
}
}
// insert element x
void insert(int x){
heap.push_back(make_pair(x, ++this->cnt));
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
// find the index of el in heap
for(vector<int>::size_type j = 0; j < heap.size(); ++j)
if (heap[j].second == i){
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().first<<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;
}