AcWing 838. 堆排序
原题链接
简单
作者:
从前
,
2021-05-22 14:03:40
,
所有人可见
,
阅读 208
#include<iostream>
#include<cstdio>
using namespace std;
const int N = 1e5 + 10;
int h[N], cnt;
int n, m;
void down(int u) {
int t = u;
if( u * 2 <= cnt && h[u * 2] < h[t]) t = 2 * u; //根节点分别和两个叶节点比较,所以没用if else语句;
if(u * 2 + 1 <= cnt && h[u * 2 + 1] < h[t]) t = u * 2 + 1;
if( u != t) {
swap(h[u], h[t]);
down(t);//把根节点继续down
}
}
int main() {
scanf("%d%d", &n, &m);
for(int i = 1; i <= n; i++) scanf("%d",&h[i]);
cnt = n;
for(int i = n / 2; i; i--) down(i);
while(m--) {
printf("%d ",h[1]);
h[1] = h[cnt--];
down(1);
}
puts("");
return 0;
}