Pagini recente » Cod sursa (job #1676127) | Cod sursa (job #2299790) | Cod sursa (job #1996317) | Cod sursa (job #2348986) | Cod sursa (job #3130085)
#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;
vector<int> elem;
vector<int> pos;
public:
MinHeap(){
heap = {};
elem = {0};
pos = {0};
}
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]);
swap(pos[heap[2*poz+1].second], pos[heap[poz].second]);
repairHeapDown(2*poz+1);
return;
}
else return;
}
else{
if(heap[2*poz+2].first < heap[poz].first){
swap(heap[2*poz+2], heap[poz]);
swap(pos[heap[2*poz+2].second], pos[heap[poz].second]);
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]);
swap(pos[heap[poz].second], pos[heap[dad].second]);
poz = dad;
}
else break;
}
}
// insert element x
void insert(int x){
elem.push_back(x);
pos.push_back(++cnt);
heap.push_back(make_pair(x, 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
// int el = elem[i];
// find the index of el in heap
int idx = pos[i]-1;
// delete the element at index i from the heap
heap[idx] = heap[heap.size()-1];
pos[heap[heap.size()-1].second] = pos[heap[idx].second];
pos[heap[idx].second] = -1;
elem[heap[idx].second] = -1;
heap.pop_back();
repairHeapDown(idx);
repairHeapUp(idx);
}
// 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;
}