定义
最大堆: 一个完全二叉树结构体。同时满足所有父节点大于等于子节点。
最大堆: 一个完全二叉树结构体。同时满足所有父节点小于等于子节点。
性质
- 对于最大堆,根节点是最大值
- 对于N个节点的堆,其深度为 O ( l g N ) O(lgN) O(lgN).
Code: MinHeap
代码应该没问题,在洛谷里全AC。
#include <cstring>
template <typename ValueType>
class MinHeap{
public:
MinHeap();
~MinHeap();
void push(ValueType const &n);
void pop();
ValueType top();
int size();
bool empty();
private:
ValueType* heap;
int len;
};
template <typename ValueType>
MinHeap<ValueType>::MinHeap(){
heap = new ValueType[10001];
len = 0;
memset(heap, 0, sizeof(heap));
}
template <typename ValueType>
MinHeap<ValueType>::~MinHeap(){
delete []heap;
}
template <typename ValueType>
void MinHeap<ValueType>::push(ValueType const & n){
heap[++len] = n;
int son = len, father = son / 2;
ValueType tmp;
while(heap[son] < heap[father] && father >= 1){
swap(heap[son],heap[father]);
son = father, father = son / 2;
}
}
template <typename ValueType>
void MinHeap<ValueType>::pop(){
swap(heap[1],heap[len]);
heap[len--] = 0;
int father = 1, son = 2;
while(son <= len){
if(son < len && heap[son] > heap[son+1]) son++;
if(heap[father] > heap[son]){
swap(heap[father], heap[son]);
father = son, son = father * 2;
}
else break;
}
}
template <typename ValueType>
ValueType MinHeap<ValueType>::top(){
return heap[1];
}
template <typename ValueType>
int MinHeap<ValueType>::size(){
return len;
}
template <typename ValueType>
bool MinHeap<ValueType>::empty(){
return len;
}
Code: MaxHeap
#include <cstring>
template <typename ValueType>
class MaxHeap{
public:
MaxHeap();
~MaxHeap();
void push(ValueType const &n);
void pop();
ValueType top();
int size();
bool empty();
private:
ValueType* heap;
int len;
};
template <typename ValueType>
MaxHeap<ValueType>::MaxHeap(){
heap = new ValueType[10001];
len = 0;
memset(heap, 0, sizeof(heap));
}
template <typename ValueType>
MaxHeap<ValueType>::~MaxHeap(){
delete []heap;
}
template <typename ValueType>
void MaxHeap<ValueType>::push(ValueType const & n){
heap[++len] = n;
int son = len, father = son / 2;
ValueType tmp;
while(heap[son] > heap[father] && father >= 1){
swap(heap[son],heap[father]);
son = father, father = son / 2;
}
}
template <typename ValueType>
void MaxHeap<ValueType>::pop(){
swap(heap[1],heap[len]);
heap[len--] = 0;
int father = 1, son = 2;
while(son <= len){
if(son < len && heap[son] < heap[son+1]) son++;
if(heap[father] < heap[son]){
swap(heap[father], heap[son]);
father = son, son = father * 2;
}
else break;
}
}
template <typename ValueType>
ValueType MaxHeap<ValueType>::top(){
return heap[1];
}
template <typename ValueType>
int MaxHeap<ValueType>::size(){
return len;
}
template <typename ValueType>
bool MaxHeap<ValueType>::empty(){
return len;
}
本文深入探讨了堆数据结构,包括最大堆和最小堆的概念、性质及实现代码。详细介绍了堆作为完全二叉树的特性,以及如何通过模板类在C++中实现堆的插入、删除和查找操作。
1万+

被折叠的 条评论
为什么被折叠?



