AcWing 838. 堆排序(模板)
程序员文章站
2022-03-31 20:03:00
...
题目链接:点击这里
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
const int N = 100010;
int h[N], sz;
int n, m;
//O(logn)
void down(int u)
{
int t = u;
if(u * 2 <= sz && h[u * 2] < h[t]) t = u * 2;
if(u * 2 + 1 <= sz && h[u * 2 + 1] < h[t]) t = u * 2 + 1;
if(t != u)
{
swap(h[u], h[t]);
down(t);
}
}
int main()
{
scanf("%d%d", &n, &m);
for(int i = 1; i <= n; ++i) scanf("%d", &h[i]);
sz = n;
for(int i = n / 2; i; --i) down(i); //O(n)建堆
while(m--)
{
printf("%d ", h[1]);
h[1] = h[sz];
sz--;
down(1);
}
return 0;
}