原题链接 :838.堆排序
输入一个长度为 n 的整数数列,从小到大输出前 m 小的数。
输入格式
第一行包含整数 n 和 m。
第二行包含 n 个整数,表示整数数列。
输出格式
共一行,包含 m 个整数,表示整数数列中前 m 小的数。
数据范围
1≤m≤n≤105,
1≤数列中元素≤109
输入样例:
5 3
4 5 1 3 2
输出样例:
1 2 3
主要思路
–by yxc
#include <bits/stdc++.h>
using namespace std;
const int N=1e6+10;
int n,m;
int heap[N],cnt;//存放节点,总节点数
void down(int u)
{
int t=u;
if(u*2<=cnt&&heap[u*2]<heap[t])
t=u*2;
if(u*2+1<=cnt&&heap[u*2+1]<heap[t])
t=u*2+1;
//找出该节点与孩子节点之中的最小节点
if(u!=t)//交换节点
{
swap(heap[u],heap[t]);
down(t);
}
}
int main()
{
cin>>n>>m;
for(int i=1;i<=n;i++)
cin>>heap[i];
cnt=n;
for(int i=n/2;i;i--)//从n/2处开始构建堆,时间复杂度O(n)
down(i);
while(m--)
{
cout<<heap[1]<<' ';//每次输出根节点,即最小值
heap[1]=heap[cnt--];//用最后一个节点覆盖根节点
down(1);
}
return 0;
}