输入一个长度为 nn 的整数数列,从小到大输出前 mm 小的数。
输入格式
第一行包含整数 nn 和 mm。
第二行包含 nn 个整数,表示整数数列。
输出格式
共一行,包含 mm 个整数,表示整数数列中前 mm 小的数。
数据范围
1≤m≤n≤1051≤m≤n≤105,
1≤数列中元素≤1091≤数列中元素≤109
输入样例:
5 3
4 5 1 3 2
输出样例:
1 2 3
C++
#include<iostream>
#include<algorithm>
using namespace std;
const int N = 1e5+1;
int h[N],size;
void down(int x)
{
int t = x;
if(x*2<=size && h[x*2]<h[t]) t = x*2;
if(x*2+1<=size && h[x*2+1]<h[t]) t = x*2+1;
if(t!=x){
swap(h[t],h[x]);
down(t);
}
}
int main()
{
int n,m;
cin>>n>>m;
for(int i=1;i<=n;i++) cin>>h[i];
size = n;
for(int i=n/2;i!=0;i--) down(i);
while(m--){
cout<<h[1]<<' ';
h[1] = h[size--];
down(1);
}
return 0;
}
python
N = 100001
h = [0] * N
size = 0
def down(x):
global h, size
t = x
if x * 2 <= size and h[x * 2] < h[t]:
t = x * 2
if x * 2 + 1 <= size and h[x * 2 + 1] < h[t]:
t = x * 2 + 1
if t != x:
temp = h[t]
h[t] = h[x]
h[x] = temp
down(t)
def main():
global h, size
n, m = map(int, input().split(" "))
h = list(map(int, input().split(" ")))
h.insert(0, 0) #因为堆要从数组下标为1开始,所以必须要在下标为0的位置插入一个数,让所有数整体后移一位
size = n
i = int(n / 2)
while i != 0:
down(i)
i -= 1
for i in range(m):
print(h[1], end=" ")
h[1] = h[size]
size -= 1
down(1)
main()