最小堆C++实现:(可以插入一个数、删除最小值)
#include <iostream>
using namespace std;
const int DefaultSize = 1000005;
template<class T>
class MinHeap{
T* heap;
int currentSize;
int maxHeapSize;
void siftDown(int start);
void siftUp(int start);
public:
MinHeap(int sz=DefaultSize);
MinHeap(T arr[], int n);
~MinHeap(){delete[] heap;}
bool Insert(const T& x);
bool Remove();
void Print();
T get_min() const {if(currentSize!=0) return heap[0]; return 0;}
bool IsEmpty() const {return currentSize==0;}
bool IsFull() const {return currentSize==maxHeapSize;}
int get_maxHeapSize() const {return maxHeapSize;}
int get_currentSize() const {return currentSize;}
};
template<class T>
MinHeap<T>::MinHeap(int sz){
if(sz<DefaultSize) sz=DefaultSize;
heap = new T[sz];
currentSize = 0;
maxHeapSize = sz;
}
template<class T>
MinHeap<T>::MinHeap(T arr[], int n){
int sz = n*2;
if(sz<DefaultSize) sz=DefaultSize;
heap = new T[sz];
for(int i=0;i<n;i++) heap[i] = arr[i];
currentSize = n;
maxHeapSize = sz;
int start = (currentSize-1-1)/2;
while(start>=0){
siftDown(start);
start--;
}
}
template<class T>
void MinHeap<T>::siftDown(int start){
int i=start, j=i*2+1;
int temp=heap[i];
while(j<=currentSize-1){
if(j+1<=currentSize-1&&heap[j+1]<heap[j]) j++;
if(temp<=heap[j]) break;
heap[i]=heap[j];
i=j;
j=i*2+1;
}
heap[i]=temp;
}
template<class T>
void MinHeap<T>::siftUp(int start){
int j=start, i=(j-1)/2;
int temp=heap[j];
while(j>0){
if(heap[i]<=temp) break;
heap[j]=heap[i];
j=i;
i=(j-1)/2;
}
heap[j]=temp;
}
template<class T>
void MinHeap<T>::Print(){
for(int i=0;i<currentSize;i++){
cout<<heap[i]<<" ";
}
cout<<endl;
}
template<class T>
bool MinHeap<T>::Insert(const T& x){
if(currentSize==maxHeapSize){
cerr<<"Heap Full"<<endl;
return false;
}
heap[currentSize] = x;
siftUp(currentSize);
currentSize++;
return true;
}
template<class T>
bool MinHeap<T>::Remove(){
if(currentSize==0){
cerr<<"Heap Empty"<<endl;
return false;
}
heap[0]=heap[currentSize-1];
currentSize--;
siftDown(0);
return true;
}
int main()
{
MinHeap<int> hp;
int n;cin>>n;
for(int i=1;i<=n;i++){
int op;cin>>op;
if(op==1){
int num;cin>>num;
hp.Insert(num);
}
else if(op==2){
cout<<hp.get_min()<<endl;
}
else{
hp.Remove();
}
}
return 0;
}
堆可以维护一组数中的最大值/最小值
参考: