Pagini recente » Cod sursa (job #3134046) | Cod sursa (job #1054504) | Cod sursa (job #1949403) | Cod sursa (job #1840460) | Cod sursa (job #2453138)
#include <vector>
#include <fstream>
using std::swap;
using std::vector;
std::ifstream fin("heapuri.in");
std::ofstream fout("heapuri.out");
class Heap {
private:
int n;
vector<int> a;
vector<int> b;
vector<int> p;
void heapify(int i) {
int min = i;
if (2 * i <= n && a[2 * i] < a[i])
min = 2 * i;
if (2 * i + 1 <= n && a[2 * i + 1] < a[min])
min = 2 * i + 1;
if (min != i) {
swap(a[i], a[min]);
swap(b[i], b[min]);
swap(p[b[i]], p[b[min]]);
heapify(min);
}
}
void decreaseKey(int i) {
while (i > 1 && a[i] < a[i / 2]) {
swap(a[i], a[i / 2]);
swap(b[i], b[i / 2]);
swap(p[b[i]], p[b[i / 2]]);
i /= 2;
}
}
public:
Heap()
: n(0), a(1), b(1), p(1) { }
int top() {
return a[1];
}
void pop(int x) {
a[p[x]] = a[n];
b[p[x]] = b[n];
p[b[n]] = p[x];
n--;
a.pop_back();
b.pop_back();
decreaseKey(p[x]);
heapify(p[x]);
}
void push(int key) {
a.push_back(key);
b.push_back(p.size());
p.push_back(++n);
decreaseKey(n);
}
};
int main() {
Heap heap;
vector<int> past;
int q; fin >> q;
for (int i = 0; i < q; i++) {
int type; fin >> type;
if (type == 1) {
int x; fin >> x;
past.push_back(x);
heap.push(x);
}
else if (type == 2) {
int x; fin >> x;
heap.pop(x);
}
else
fout << heap.top() << '\n';
}
fout.close();
return 0;
}