图的开始--第六天打卡之最大/最小堆
作者:
lgd123
,
2021-07-30 12:47:36
,
所有人可见
,
阅读 234
/*最大/最小堆
最大堆、最小堆的实现模板。
*/
//最大堆
#include<iostream>
using namespace std;
const int N = 500010;
long long a[N],n;
void maxHeapify(long long a[],int i)
{
int l ,r , largest;
l = 2*i;
r = 2*i+1;
if(l<=n&&a[l]>a[i]) largest = l;
else largest = i;
if(r<=n&&a[r]>a[largest]) largest = r;
if(largest != i)
{
swap(a[i],a[largest]);
maxHeapify(a,largest);
}
}
void buildMaxHeap(long long a[])
{
for(int i = n/2;i>0;i--)
{
maxHeapify(a,i);
}
}
int main()
{
cin>>n;
for(int i = 1 ;i <= n ; i ++) cin>>a[i];
buildMaxHeap(a);
for(int i= 1 ;i <= n ;i ++)
{
cout<<" "<<a[i];
}
cout<<endl;
return 0;
}
//最小堆:这里只给出核心部分的代码....
void minHeapify(long long a[],int i)
{
int l ,r , minn;
l = 2*i;
r = 2*i+1;
if(l<=n&&a[l]<a[i]) minn = l;
else minn = i;
if(r<=n&&a[r]<a[minn]) minn = r;
if(minn != i)
{
swap(a[i],a[minn]);
minHeapify(a,minn);
}
}