内容
创建 最小堆类。最小堆的存储结构使用 数组。提供操作:插入、删除、初始化。题目第一个操作是建堆操作,接下来是对堆的插入和删除操作,插入和删除都在建好的堆上操作。
格式
输入
第一行一个数n(n<=5000),代表堆的大小。第二行n个数,代表堆的各个元素。
第三行一个数m (m<=1000),代表接下来共m个操作。接下来m行,分别代表各个操作。下面是各个操作的格式:
插入操作:1 num
删除操作:2
排序操作:第一行两个数3和n,3代表是排序操作,n代表待排序的数的数目,接下来一行n个数是待排序数
保证排序操作只出现一次且一定是最后一个操作。
输出
第一行建堆操作输出建好堆后堆顶的元素。
接下来m个操作,若是插入和删除操作,每行输出执行操作后堆顶的元素的值;若是排序操作,输出一行按升序排序好的结果,每个元素间用空格分隔。
#include<iostream>
using namespace std;
template<class T>
void changeLength(T *&a,int oldLength,int newLength){
T *temp=new T[newLength];
int number=oldLength<newLength?oldLength:newLength;
for(int i=0;i<number;i++){
temp[i]=a[i];
}
delete []a;
a=temp;
}
template<class T>
class MinHeap{
private:
T *heap;
int arrayLength;//数组heap的容量
int heapSize;//堆的元素个数
public:
MinHeap(int size=10);
~MinHeap(){
delete []heap;}
bool queueEmpty()const{
return heapSize==0;}
int size() const{
return heapSize;}
const T&top(){
return heap[1];}
void push(const T&theElement);
void pop();
};
template<class T>
MinHeap<T>::MinHeap(int size){
arrayLength=size+1;
heap=new T[arrayLength];
heapSize=0;
}
template<class T>
void MinHeap<T>::push(const T&theElement){
if(heapSize==arrayLength-1){
changeLength(heap,arrayLength,2*arrayLength);
arrayLength*=2;
}
//为元素寻找插入位置
//currentnode从新叶子向上移动
int currentNode=++heapSize;
while(currentNode!=1&&heap[currentNode/2]>theElement){
heap[currentNode]=heap[currentNode/2];//把元素向下移动
currentNode=currentNode/2;//currentNode移向双亲
}
heap[currentNode]=theElement;
}
template<class T>
void MinHeap<T>::pop(){
// if(heapSize==0){
// throw queueEmpty();
// }
heap[1].~T();//删除最小元素
//T删除最后一个元素,然后重新键堆
T lastElement=heap[heapSize--];
//从根开始,为最后一个元素寻找位置
int currentNode=1,child=2;
while(child<=heapSize){
//heap[child]应该是currentNode的更小的孩子
if(child<heapSize&&heap[child]>heap[child+1])
child++;
//可以把lastElement放在heap[currentNode]吗?
if(lastElement<=heap[child])
break;//可以
//否则不可以
heap[currentNode]=heap[child];//把孩子向上移动
currentNode=child;
child*=2;
}
heap[currentNode]=lastElement;
}
int main(){
int n;cin>>n;
MinHeap<int>minheap(n);
for(int i=0;i<n;i++){
int x;cin>>x;
minheap.push(x);
}
cout<<minheap.top()<<endl;
int m,num;cin>>m;
int op,times=0;
for(int i=0;i<m;i++){
cin>>op;
if(op==1){
cin>>num;
minheap.push(num);
cout<<minheap.top()<<endl;
}else if(op==2){
minheap.pop();
cout<<minheap.top()<<endl;
}else if(op==3){
int k;cin>>k;
MinHeap<int> minheap1(k);
for(int i=0;i<k;i++){
int number;cin>>number;
minheap1.push(number);
}
for(int i=0;i<k;i++){
cout<<minheap1.top()<<" ";
minheap1.pop();
}
}
}
return 0;
}