Pagini recente » Cod sursa (job #2196742) | Cod sursa (job #2287839) | Cod sursa (job #63765) | Cod sursa (job #1929679) | Cod sursa (job #3129874)
#include <iostream>
#include <algorithm>
#include <vector>
#include <unordered_map>
#include <fstream>
using namespace std;
ifstream f("heapuri.in");
ofstream g("heapuri.out");
class MinHeap{
private:
int cnt = 0;
vector<int> heap;
unordered_map<int, int> pos;
public:
MinHeap(){
heap = {};
pos = {};
}
void print(){
for(vector<int>::size_type 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.insert(make_pair(++this->cnt, 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];
cout<<el<<endl;
// find the index of el in heap
auto it = find(heap.begin(), heap.end(), el);
int index = distance(heap.begin(), it);
cout<<index<<endl;
// delete the element at index i from the heap
heap[index] = heap[heap.size()-1];
heap.pop_back();
repairHeapDown(index);
repairHeapUp(index);
}
// 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;
}