AcWing 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
【算法分析】
● 堆是一棵完全二叉树。堆可以用一个一维数组(建议下标从 1 开始)进行模拟。
● 堆的数组模拟实现,参见:https://blog.csdn.net/hnjzsyjyj/article/details/146358448
【算法代码:堆排序】
#include<bits/stdc++.h>
using namespace std;
const int maxn=1e5+5;
int h[maxn];
int tot;
int n,m;
void down(int u) {
int t=u;
if(u*2<=tot && h[u*2]<h[t]) t=u*2;
if(u*2+1<=tot && h[u*2+1]<h[t]) t=u*2+1;
if(u!=t) {
swap(h[u],h[t]);
down(t);
}
}
int main() {
cin>>n>>m;
tot=n;
for(int i=1; i<=n; i++) cin>>h[i];
for(int i=n/2; i>=1; i--) down(i);
while(m--) {
cout<<h[1]<<" ";
h[1]=h[tot--];
down(1);
}
return 0;
}
/*
in:
5 3
4 5 1 3 2
out:
1 2 3
*/
【算法代码:sort】
#include <bits/stdc++.h>
using namespace std;
const int maxn=1e5+5;
int a[maxn];
int main() {
int n,m;
cin>>n>>m;
for(int i=1; i<=n; i++) cin>>a[i];
sort(a+1,a+1+n);
//unique(a+1,a+1+n);
for(int i=1; i<=m; i++) cout<<a[i]<<" ";
return 0;
}
/*
in:
5 3
4 5 1 3 2
out:
1 2 3
*/
【参考文献】
https://blog.csdn.net/hnjzsyjyj/article/details/146331059
https://blog.csdn.net/hnjzsyjyj/article/details/146358448
https://www.acwing.com/solution/content/6362/
https://www.acwing.com/solution/content/5541/