#include <iostream>
#include <string.h>
using namespace std;
template <class T>
class Heap {
public:
Heap():n(), capacity() {
this->arr = new T[capacity];
}
~Heap() {
delete[] arr;
}
void insert(T v) {
if (n >= capacity) {
T* tmp = new T[capacity << ];
memcpy(tmp, arr, sizeof(T) * capacity);
capacity <<= ;
}
arr[n++] = v;
shiftUp(n - );
}
void del(int index) {
if (index < || index >= n) return;
swap(arr[index], arr[n - ]);
shiftDown(index, --n);
}
void shiftDown(int st, int ed) {
T tmp = arr[st];
while (st < ed) {
int next = -;
int left = st * + ; // left child node
if (left < ed) next = left;
else break;
int right = st * + ;
if (right < ed && arr[right] < arr[next]) next = right;
if (arr[next] < arr[st]) {
arr[st] = arr[next];
st = next;
} else break;
}
arr[st] = tmp;
}
void shiftUp(int ed) {
T tmp = arr[ed];
while (ed > ) {
int parent = (ed - ) / ;
if (arr[ed] < arr[parent]) {
arr[ed] = arr[parent];
ed = parent;
} else break;
}
arr[ed] = tmp;
}
void sort() {
for (int j = n - ; j >= ; --j) {
swap(arr[], arr[j]);
shiftDown(, j); // here should be j
}
}
void print() const {
for (int i = ; i < n; ++i) {
cout << arr[i] << " ";
}
cout << endl;
}
T get(int pos) {
return arr[pos];
}
void update(int pos, int v) {
if (pos < || pos >= n) return;
if (arr[pos] < v) {
arr[pos] = v;
shiftDown(pos, n);
} else {
shiftUp(pos);
}
}
void increase(int pos, int v) {
if (pos < || pos >= n) return;
arr[pos] = arr[pos] + v;
shiftDown(pos, n);
}
void decrease(int pos, int v) {
if (pos < || pos >= n) return;
arr[pos] = arr[pos] - v;
shiftUp(pos);
}
bool empty() const {
return n <= ;
}
void pop() {
if (empty()) return;
del();
}
T top() {
if (empty()) return;
return arr[];
}
private:
T* arr;
int n;
int capacity;
};
int main()
{
int arr[] = {, ,,,,};
Heap<int> heap;
for (int i = ; i < ; ++i) {
heap.insert(arr[i]);
}
//heap.sort();
heap.print();
heap.del();
heap.print();
heap.increase(, );
heap.print();
return ;
}