Pagini recente » Rating Nituica Andrei-Sebastian (zugafa) | Cod sursa (job #2785362) | Cod sursa (job #154763) | Cod sursa (job #2182290) | Cod sursa (job #2638514)
#include <fstream>
#include <vector>
#include <iostream>
using namespace std;
vector<int> pos;
vector<int> heap;
void swapp(vector<int>& v, int a, int b) {
int tmp = pos[a];
pos[a] = pos[b];
pos[b] = pos[a];
tmp = v[a];
v[a] = v[b];
v[b] = tmp;
}
void up_heapify(int index) {
while (index > 1 && heap[index/2] > heap[index]) {
swapp(heap, index/2, index);
index /= 2;
}
}
void down_heapify(int index) {
int left = index * 2;
int right = index * 2 + 1;
int smallest = index;
if (left < heap.size() && heap[left] < heap[index])
smallest = left;
if (right < heap.size() && heap[right] < heap[smallest])
smallest = right;
if (smallest != index) {
swapp(heap, smallest, index);
down_heapify(smallest);
}
}
void add(int num) {
// cout << "adding number " << num << endl;
heap.push_back(num);
pos.push_back(heap.size() - 1);
up_heapify(heap.size() - 1);
}
void rm(int index) {
// cout << "removing element no " << index << " which is " << heap[pos[index]] << " on position " << pos[index] << endl;
heap[pos[index]] = heap[heap.size() - 1];
pos[index] = heap.size() - 1;
heap.pop_back();
down_heapify(index);
}
void print_vec(vector<int> &vec) {
for (int i = 1; i < vec.size(); ++i) {
cout << vec[i] << " ";
}
cout <<endl;
}
int main() {
ifstream in;
ofstream out;
in.open("heapuri.in");
out.open("heapuri.out");
int n;
in >> n;
heap.push_back(99998);
pos.push_back(-11112);
int type, num;
for (int i = 0; i < n; ++i) {
in >> type;
if (type != 3)
in >> num;
switch (type) {
case 1: add(num); print_vec(heap); print_vec(pos); break;
case 2: rm(num); print_vec(heap); print_vec(pos); break;
case 3: out << heap[1] << '\n'; break;
}
}
in.close();
out.close();
return 0;
}