Pagini recente » Borderou de evaluare (job #1682040) | Cod sursa (job #1247523) | Cod sursa (job #3181080) | Borderou de evaluare (job #778895) | Cod sursa (job #3233184)
#include <iostream>
#include <vector>
using namespace std;
class MinHeap {
public:
vector<int> v;
vector<int> h;
vector<int> pos;
int parent(int i) {
return (i - 1) / 2;
}
void push(int elem) {
v.push_back(elem);
h.push_back(v.size() - 1);
pos.push_back(h.size() - 1);
int i = h.size() - 1;
while (i > 0 && v[h[i]] < v[h[parent(i)]]) {
swap(pos[h[i]], pos[h[parent(i)]]);
swap(h[i], h[parent(i)]);
i = parent(i);
}
}
int top() {
return v[h[0]];
}
bool empty() {
return h.empty();
}
int left(int i) {
return (i + 1) * 2 - 1;
}
int right(int i) {
return (i + 1) * 2;
}
void pop() {
swap(pos[h[0]], pos[h[h.size() - 1]]);
swap(h[0], h[h.size() - 1]);
h.pop_back();
heapify(0);
}
void heapify(int index) {
while (true) {
int l = left(index);
int r = right(index);
int maxx = index;
if (l < h.size() && v[h[l]] < v[h[maxx]]) {
maxx = l;
}
if (r < h.size() && v[h[r]] < v[h[maxx]]) {
maxx = r;
}
if (maxx == index) {
break;
}
swap(pos[h[index]], pos[h[maxx]]);
swap(h[index], h[maxx]);
index = maxx;
}
}
void remove(int index) {
int h_index = pos[index];
swap(pos[index], pos[h[h.size() - 1]]);
swap(h[h_index], h[h.size() - 1]);
h.pop_back();
heapify(h_index);
}
};
int main() {
freopen("heapuri.in", "r", stdin);
freopen("heapuri.out", "w", stdout);
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
MinHeap heap;
int n;
cin >> n;
while (n--) {
int t;
cin >> t;
if (t == 1 || t == 2) {
int x;
cin >> x;
if (t == 1) {
heap.push(x);
} else if (t == 2) {
heap.remove(x - 1);
}
} else if (t == 3) {
cout << heap.top() << '\n';
}
}
}