838.堆排序(https://www.acwing.com/problem/content/840/)
输入一个长度为n的整数数列,从大到小输出前m小的数。
输入格式
第一行包含n和m;
第二行包含n个整数,表示整数数列。
输出格式
共一行,包含m个整数,表示整数数列中前m小的数。
数据范围
1<=m<=n<=10^5,
1<=数列中元素<=10^9
输入样例:
5 3
4 5 1 3 2
输出样例:
1 2 3
参考程序
#include<bits/stdc++.h>
using namespace std;
int len;
int h[100050];
void down(int x)
{
int t=x;
if(x*2<=len&&h[x*2]<h[t])
t=x*2;
if(x*2+1<=len&&h[x*2+1]<h[t])
t=x*2+1;
if(t!=x)
{
swap(h[t],h[x]);
down(t);
}
}
void up(int x)
{
while(h[x]<h[x/2]&&x/2)
{
swap(h[x],h[x/2]);
x/=2;
}
}
int main()
{
int n,m;
cin>>n>>m;
for(int i=1;i<=n;i++)
{
scanf("%d",&h[i]);
}
len=n;
for(int i=n/2;i>0;i--)
down(i);
while(m--)
{
cout<<h[1]<<" ";
h[1]=h[len];
len--;
down(1);
}
}