Pagini recente » Cod sursa (job #3168548) | Cod sursa (job #2828067) | Cod sursa (job #312961) | Cod sursa (job #2665386) | Cod sursa (job #1311495)
#include <stdio.h>
#include <fstream>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
ifstream in ("data.in");
ofstream out ("data.out");
/*
* The Compare operator() (T, T) return 1 if the first argument has greater
* priority than the second.
*/
template <typename T, typename Compare>
class Heap {
public:
typedef T value_type;
typedef unsigned int uint;
Heap() : vector_size(0), heap_size(0) {
// add an element so that indexing starts from 1
container.push_back(0);
}
~Heap() {}
void insert(value_type x) {
if (heap_size < vector_size) {
++heap_size;
container[heap_size] = x;
}
else {
++vector_size;
++heap_size;
container.push_back(x);
}
uint i = heap_size;
while ( i > 1 && cmp(container[i], container[ father(i) ]) ) {
swap(container[i], container[ father(i) ]);
i = father(i);
}
}
void insert_vector(value_type x) {
++vector_size;
container.push_back(x);
}
value_type extrac_vector() {
if (vector_size < 1) {
out << "Vector underflow\n";
return 0;
}
value_type last = container[vector_size];
container.pop_back();
--vector_size;
if (vector_size < heap_size)
heap_size = vector_size;
return last;
}
void clear() {
container.clear();
container.push_back(0);
heap_size = vector_size = 0;
}
value_type get_max() {
if (heap_size < 1) {
out << "Heap underflow\n";
return 0;
}
return container[1];
}
value_type extract_max() {
if (heap_size < 1) {
out << "Heap underflow\n";
return 0;
}
value_type maxx = container[1];
container[1] = container[heap_size];
--heap_size;
max_heapify(1);
return maxx;
}
void build_heap() {
heap_size = vector_size;
for (uint i = heap_size / 2; i > 0; --i)
max_heapify(i);
}
void heap_sort() {
build_heap();
for (uint i = heap_size; i > 1; --i) {
swap(container[1], container[i]);
--heap_size;
max_heapify(1);
}
heap_size = 0;
}
void print_heap() {
for (uint i = 1; i <= heap_size; ++i)
out << container[i] << ' ';
out << '\n';
}
void print_vector() {
for (uint i = 1; i <= vector_size; ++i)
out << container[i] << ' ';
out << '\n';
}
private:
uint father(uint i) { return i >> 1; }
uint left(uint i) { return i << 1; }
uint right(uint i) { return (i << 1) + 1; }
void max_heapify(uint i) {
uint largest = 0;
uint l = left(i);
uint r = right(i);
if ( l <= heap_size && cmp(container[l], container[i]) )
largest = l;
else
largest = i;
if ( r <= heap_size && cmp(container[r], container[largest]) )
largest = r;
if (largest != i) {
swap(container[largest], container[i]);
max_heapify(largest);
}
}
vector<value_type> container;
uint vector_size;
uint heap_size;
Compare cmp;
};
struct comp{
bool operator () (int i, int j) {
return i > j;
}
};
int main() {
Heap<int, comp> h;
int n;
int x;
in >> n;
for (int i = 1; i <= n; ++i) {
in >> x;
h.insert_vector(x);
}
h.heap_sort();
h.print_vector();
return 0;
}