AcWing 838. 堆排序
原题链接
简单
作者:
qpalzmczy
,
2025-04-09 21:29:56
· 广东
,
所有人可见
,
阅读 2
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int n, m, cnt, sum;
int res[N];
bool st[N];
void down(int u)
{
int t = u;
if (u * 2 <= cnt && res[u * 2] < res[t])
t = u * 2;
if (u * 2 + 1 <= cnt && res[u * 2 + 1] < res[t])
t = u * 2 + 1;
if (t != u)
{
swap(res[t], res[u]);
down(t);
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
cin >> n >> m;
cnt = n;
for (int i = 1; i <= n; i++)
cin >> res[i];
for (int i = n / 2; i; i--)
down(i);
while (m--)
{
printf("%d ", res[1]);
res[1] = res[cnt--];
down(1);
}
puts("");
return 0;
}