class Solution
{
public:
class Heap
{
private:
int* _Heap=nullptr;
//int index;
int maxsize;
public:
Heap(){}
Heap(vector<int>& nums)
{
int n=nums.size();
_Heap= new int[n];
for(auto t:nums)
_Heap[t]=nums[t];
maxsize=n;
}
~Heap(){delete [] _Heap;}
int MaxDadandSons(int i)
{
int j=2*i+1;
int k=2*i+2; //右子节点
if(k>=0 && k<=maxsize-1)
return (_Heap[j]>=_Heap[k])? ((_Heap[j]>_Heap[i])?j:i):((_Heap[k]>_Heap[i])?k:i);
else if(j>=0 && j<=maxsize-1)
return (_Heap[j]>_Heap[i])?j:i;
else
return i;
}
int delmax()
{
int max=_Heap[0];
_Heap[0]=_Heap[--maxsize];
adjustdown(0);
return max;
}
bool empty()
{
return maxsize<0;
}
protected:
virtual void adjustup(int )=0;
void adjustdown(int i)
{
int j;
while(i!=(j=MaxDadandSons(i)))
{
swap(_Heap[i],_Heap[j]);
i=j;
}
}
void heapify()
{
for(int i=(maxsize-1)>>1;i>=0;--i) //由下至上,由后至前的算法
{
adjustdown(i);
}
}
};
堆类
最新推荐文章于 2021-11-15 18:02:34 发布