Pagini recente » Cod sursa (job #2325353) | Cod sursa (job #417346) | Cod sursa (job #2529667) | Cod sursa (job #2901793) | Cod sursa (job #1248225)
#include <algorithm>
#include <fstream>
#include <vector>
using namespace std;
typedef int heap_t;
struct Heap {
vector<heap_t> data;
vector<int> heap, pos_heap;
int parent(int pos) { return (pos - 1) / 2; }
int left_child(int pos) { return 2 * pos + 1; }
int right_child(int pos) { return 2 * pos + 2; }
void swaph(int i, int j) {
swap(heap[i], heap[j]);
pos_heap[heap[i]] = i;
pos_heap[heap[j]] = j;
}
bool is_less(int i, int j) { return data[heap[i]] < data[heap[j]]; }
void up(int i) {
for (int p = parent(i); p != i && is_less(i, p); i = p, p = parent(p))
swaph(i, p);
}
void down(int i) {
int next;
while (true) {
if (left_child(i) < heap.size())
next = left_child(i);
else return;
if (right_child(i) < heap.size() && is_less(right_child(i), next))
next = right_child(i);
if (! is_less(next, i)) return;
swaph(i, next);
i = next;
}
}
void insert(int x) {
data.push_back(x);
heap.push_back(data.size() - 1);
pos_heap.push_back(heap.size() - 1);
up(heap.size() - 1);
}
void remove(int i) {
i = pos_heap[i];
swaph(i, heap.size() - 1);
heap.pop_back();
down(i);
}
int top() { return data[heap[0]]; }
} H;
int main() {
ifstream fin("heapuri.in");
ofstream fout("heapuri.out");
int q, op, x, i;
for (fin >> q; q; --q) {
fin >> op;
if (op == 1) {
fin >> x;
H.insert(x);
}
else if (op == 2) {
fin >> i;
H.remove(i-1);
}
else
fout << H.top() << endl;
}
return 0;
}