Pagini recente » Cod sursa (job #2770802) | Cod sursa (job #332821) | Cod sursa (job #1744257) | Cod sursa (job #1223998) | Cod sursa (job #1811763)
#include <bits/stdc++.h>
#define SZ(x) ((int) (x).size())
using namespace std;
template<class T>
struct Heap {
vector<T> heap;
map<T, int> posInHeap;
static bool Compare(const T& a, const T& b) {
return a < b;
}
Heap() {
}
Heap(const vector<T>& el) : heap(el) {
for (int i = 0; i < SZ(heap); i++) {
posInHeap[heap[i]] = i;
}
for (int i = SZ(heap) / 2 - 1; i >= 0; i--) {
DownHeap(i);
}
}
void DownHeap(int node) {
int bestNode; bool changed;
do {
changed = false;
bestNode = node;
if (2 * node + 1 < SZ(heap) and Compare(heap[2 * node + 1], heap[bestNode])) {
bestNode = 2 * node + 1;
}
if (2 * node + 2 < SZ(heap) and Compare(heap[2 * node + 2], heap[bestNode])) {
bestNode = 2 * node + 2;
}
if (bestNode != node) {
posInHeap[heap[node]] = bestNode;
posInHeap[heap[bestNode]] = node;
swap(heap[node], heap[bestNode]);
changed = true;
}
} while (changed);
}
void UpHeap(int node) {
int ancestor = (node - 1) / 2;
while (node > 0 and Compare(heap[node], heap[ancestor])) {
posInHeap[heap[node]] = ancestor;
posInHeap[heap[ancestor]] = node;
swap(heap[node], heap[ancestor]);
node = ancestor;
ancestor = (node - 1) / 2;
}
}
void Insert(const T& x) {
heap.emplace_back(x);
posInHeap[x] = SZ(heap) - 1;
UpHeap(posInHeap[x]);
}
void Erase(const T& x) {
const int pos = posInHeap[x];
heap[pos] = heap.back();
posInHeap.erase(x);
posInHeap[heap[pos]] = pos;
heap.pop_back();
DownHeap(pos);
}
T Top() const {
return heap.front();
}
};
int main() {
#ifdef INFOARENA
ifstream cin("heapuri.in");
ofstream cout("heapuri.out");
#endif
cin.tie(0);
ios_base::sync_with_stdio(false);
int numOp; cin >> numOp;
vector<int> v;
Heap<int> m_heap;
for (int iter = 0; iter < numOp; iter++) {
int opType; cin >> opType;
if (opType == 1) {
int x; cin >> x;
v.emplace_back(x);
m_heap.Insert(x);
} else if (opType == 2) {
int idx; cin >> idx;
m_heap.Erase(v[idx - 1]);
} else {
cout << m_heap.Top() << '\n';
}
}
}