来源:acwing(侵删)
一维数组对堆的存储:你没见过的船新版本
一些操作:down(x),up(y)两个移动堆点的函数
down函数 堆排序:
#include<bits/stdc++.h>
using namespace std;
#define IOS ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
const int N=1e5+10;
int h[N];
int n,m,co;
void down(int x)
{
int t=x;
if(2*x <= co && h[2*x]<h[t]) t=2*x;
if(2*x+1 <= co && h[2*x+1]<h[t]) t=2*x+1;
if(t!=x)
{
swap(h[x],h[t]);
down(t);
}
}
int main()
{
IOS
cin>>n>>m;
for(int i=1;i<=n;i++) cin>>h[i];co=n;
for(int i=n/2;i;i--) down(i);
while(m--)
{
cout<<h[1]<<' ';
h[1]=h[co--];
down(1);
}
return 0;
}