#include <iostream>
using namespace std;
class MinHeap{
private:
int *heap;
int currentsize;
int maxsize;
public:
MinHeap(int sz){
maxsize=sz;
heap=new int[maxsize];
if(heap==NULL){
cerr<<"distribute error!"<<endl;
exit(1);
}
currentsize=0;
}
~MinHeap(){
delete[]heap;
}
bool Insert(const int x);
bool RemoveMin(int& x);
bool IsEmpty(){
return (currentsize==0)?true:false;
}
bool IsFull(){
return (currentsize==maxsize)?true:false;
}
void makeEmpty(){
currentsize=0;
}
void shiftdown(int start);
void shiftup(int start);
};
void MinHeap::shiftdown(int start){
int i=start;
int j=(heap[i*2+1]<heap[i*2+2])?i*2+1:i*2+2;
int temp=heap[start];
while(j<currentsize){
if(temp<=heap[j]){
break;
}
heap[i]=heap[j];
i=j;
j=(heap[i*2+1]<heap[i*2+2])?i*2+1:i*2+2;
}
heap[i]=temp;
}
void MinHeap::shiftup(int start){
int i=start;
int j=(i-1)/2;
int temp=heap[i];
while(i>0){
if(temp>=heap[j]){
break;
}
if(temp<heap[j]){
heap[i]=heap[j];
i=j;
j=(i-1)/2;
}
}
heap[i]=temp;
}
bool MinHeap::Insert(const int x){
if(IsFull()){
cerr<<"Heap Full"<<endl;
return false;
}
heap[currentsize]=x;
shiftup(currentsize);
currentsize++;
return true;
}
bool MinHeap::RemoveMin(int& x){
if(IsEmpty()){
cerr<<"Heap Empty"<<endl;
return false;
}
x=heap[0];
heap[0]=heap[currentsize-1];
shiftdown(0);
currentsize--;
return true;
}
int main(){
MinHeap t(1002);
cout<<"Insert 1 Remove 2 Exit 3"<<endl;
int f;
while(1){
cin>>f;
if(f==1){
int num,c;
cout<<"number of num:";
cin>>c;
while(c--){
cin>>num;
if(t.Insert(num)){
cout<<"Success!"<<endl;
}
}
}
else if(f==2){
int x;
if(t.RemoveMin(x)){
cout<<"The Min num:"<<x<<endl;
}
}
else if(f==3){
break;
}
else{
cout<<"Your input is illegal"<<endl;
break;
}
}
return 0;
}
最小堆实现优先级队列
最新推荐文章于 2024-07-20 09:57:49 发布