Pagini recente » Cod sursa (job #3207591) | Cod sursa (job #1148925) | Cod sursa (job #689953) | Cod sursa (job #1067846) | Cod sursa (job #2078467)
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
typedef unsigned int uint;
class heap {
private:
uint capacity;
uint size;
uint data_size;
int* data;
uint* nodes;
uint* positions;
void push_up(uint index);
void push_down(uint index);
void swap(uint first_index, uint second_index);
public:
heap(uint capacity);
~heap();
void insert(int item);
void remove(uint index);
int get_min();
};
heap::heap(uint capacity) : size(0), capacity(capacity) {
data = new int[capacity + 1];
nodes = new uint[capacity + 1];
positions = new uint[capacity + 1];
}
heap::~heap() {
delete[] data;
delete[] nodes;
delete[] positions;
}
void heap::push_up(uint index) {
if (index <= 1) {
return;
}
uint parent_index = index >> 1;
if (data[nodes[parent_index]] > data[nodes[index]]) {
swap(parent_index, index);
push_up(parent_index);
}
}
void heap::push_down(uint index) {
if (index >= size) {
return;
}
uint left_son_index = index << 1;
uint right_son_index = left_son_index | 1;
uint son_index = index;
if (left_son_index <= size && data[nodes[left_son_index]] < data[nodes[index]]) {
son_index = left_son_index;
}
if (right_son_index <= size && data[nodes[right_son_index]] < data[nodes[son_index]]) {
son_index = right_son_index;
}
if (son_index != index) {
swap(index, son_index);
push_down(son_index);
}
}
void heap::swap(uint first_index, uint second_index) {
uint aux_nodes = nodes[first_index];
nodes[first_index] = nodes[second_index];
nodes[second_index] = aux_nodes;
positions[nodes[first_index]] = first_index;
positions[nodes[second_index]] = second_index;
}
void heap::insert(int item) {
data[++data_size] = item;
nodes[++size] = data_size;
positions[data_size] = size;
push_up(size);
}
void heap::remove(uint index) {
data[index] = -1;
push_up(positions[index]);
positions[nodes[1]] = 0;
nodes[1] = nodes[size--];
positions[nodes[1]] = 1;
push_down(1);
}
int heap::get_min() {
return data[nodes[1]];
}
int main() {
ifstream in("heapuri.in");
ofstream out("heapuri.out");
int num_operations;
in >> num_operations;
heap the_heap(num_operations);
for (int i = 0; i < num_operations; ++i) {
int operation_type;
in >> operation_type;
if (1 == operation_type) {
int value;
in >> value;
the_heap.insert(value);
} else if (2 == operation_type) {
uint index;
in >> index;
the_heap.remove(index);
} else {
out << the_heap.get_min() << endl;
}
}
in.close();
out.close();
return 0;
}