#pragma once
#include <iostream>
using namespace std;
void swap(int a, int b, int *x) {
int t = x[a];
x[a] = x[b];
x[b] = t;
}
class Heap {
private:
int *heap;
int maxSize;
int n;
void siftdown(int pos) {
while(!isLeaf(pos)){
int rc = rightchildren(pos);
int j = leftchildren(pos);
if ((rc < n) &&( heap[j] < heap[rc]))
j = rc;
if (heap[pos] > heap[j])
return;
swap(pos, j, heap);
pos = j;
}
}
public:
Heap(int sz, int num,int *a) {
maxSize = sz;
n = num;
heap = a;
buildHeap();
}
bool isLeaf(int pos)const {
return (pos >= n / 2) && (pos < n);
}
int rightchildren(int pos)const {
return 2 * pos + 2;
}
int leftchildren(int pos)const {
return 2 * pos + 1;
}
int parent(int pos) const{
return (pos - 1) / 2;
}
void buildHeap() {
for (int i = n / 2 - 1; i >= 0; i--) {
siftdown(i);
}
}
void insert(const int& it) {
int curr = n++;
heap[curr] = it;
while ((curr != 0) && (heap[curr] > heap[parent(curr)]) ){
swap(curr, parent(curr), heap);
curr = parent(curr);
}
}
int removefirst() {
swap(0, --n, heap);
if (n != 0)siftdown(0);
return heap[n];
}
int remove(int pos) {
if (pos == n - 1)--n;
else {
swap(pos, --n, heap);
while ((pos != 0) && heap[pos] > heap[parent(pos)]) {
swap(pos, parent(pos), heap);
pos = parent(pos);
}
if (n != 0)siftdown(pos);
}
return heap[n];
}
};
转载于:https://my.oschina.net/u/3772904/blog/1616345