Pagini recente » Cod sursa (job #689477) | Cod sursa (job #779571) | Cod sursa (job #519090) | Cod sursa (job #2352182) | Cod sursa (job #1093762)
#include <algorithm>
#include <fstream>
#include <iostream>
#include <vector>
using namespace std;
class Heap {
public:
Heap() {
}
void insert(int value) {
values.push_back(value);
positions.push_back(heap.size());
heap.push_back(positions.size()-1);
up(heap.size() - 1);
}
void remove(int position) {
values[position] = -1;
up(positions[position]);
hswap(0, heap.size()-1);
heap.pop_back();
down(0);
}
int min() {
return values[heap[0]];
}
private:
vector<int> values;
vector<int> heap;
vector<int> positions;
int up(int x) {
while (x > 0 && values[heap[x]] < values[heap[x/2]]) {
hswap(x, x/2);
x /= 2;
}
return x;
}
int down(int x) {
while (true) {
int son = x * 2 + 1;
if (son >= heap.size()) return x;
if (son+1 < heap.size() && values[heap[son+1]] < values[heap[son]]) son ++;
if (values[heap[x]] > values[heap[son]]) {
hswap(x, son);
x = son;
} else {
return x;
}
}
}
void hswap(int p1, int p2) {
swap(positions[heap[p1]], positions[heap[p2]]);
swap(heap[p1], heap[p2]);
}
void print() {
for (int i=0; i<heap.size(); ++i)
cout << values[heap[i]] << " ";
}
};
int main() {
ifstream in("heapuri.in");
ofstream out("heapuri.out");
int nq;
Heap h;
in >> nq;
while (nq --) {
int op, val;
in >> op;
switch (op) {
case 1:
in >> val;
h.insert(val);
break;
case 2:
in >> val;
h.remove(val-1);
break;
case 3:
out << h.min() << "\n";
break;
}
}
out.close();
return 0;
}