838. 堆排序,

完全二叉树手写小根堆

堆排序的五大功能

1.插入一个数

2.求集合当中的最小值

3.删除最小值

4.删除任意一个元素

5.修改任意一个元素

最后两个功能stl中的堆即优先队列都没法直接实现

输入一个长度为 n 的整数数列,从小到大输出前 m 小的数。

输入格式

第一行包含整数 n 和 m。

第二行包含 n 个整数,表示整数数列。

输出格式

共一行,包含 m 个整数,表示整数数列中前 m 小的数。

数据范围

1≤m≤n≤105,

1≤数列中元素≤109

输入样例:
5 3
4 5 1 3 2
输出样例:
1 2 3

解析:

此代码的第一次排序时间复杂的为 O(n)

cpp 复制代码
#include<iostream>
#include<string>
#include<cstring>
#include<cmath>
#include<ctime>
#include<algorithm>
#include<utility>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<math.h>
#include<map>

using namespace std;
typedef long long LL;
const int N = 1e5 + 5, M = 3e5 + 5;
int n, m;
int h[N],cnt;

void down(int u) {
	int t = u;
	if (u * 2 <= cnt && h[2 * u] < h[t])t = 2 * u;
	if (2 * u + 1 <= cnt && h[2 * u + 1] < h[t])t = 2 * u + 1;
	if (u != t) {
		swap(h[t], h[u]);
		down(t);
	}
}

int main() {
	cin >> n >> m;
	for (int i = 1; i <= n; i++)scanf("%d", &h[i]);
	cnt = n;
	for (int i = n / 2; i; i--)down(i);//时间复杂度为 O(n)
	
	while (m--) {
		printf("%d ", h[1]);
		h[1] = h[cnt];
		cnt--;
		down(1);
	}
	return 0;
}
相关推荐
penguin_bark1 分钟前
69. x 的平方根
算法
FL16238631294 分钟前
[C++]使用纯opencv部署yolov11-pose姿态估计onnx模型
c++·opencv·yolo
sukalot8 分钟前
windows C++-使用任务和 XML HTTP 请求进行连接(一)
c++·windows
一休哥助手10 分钟前
Redis 五种数据类型及底层数据结构详解
数据结构·数据库·redis
这可就有点麻烦了11 分钟前
强化学习笔记之【TD3算法】
linux·笔记·算法·机器学习
苏宸啊17 分钟前
顺序表及其代码实现
数据结构·算法
lin zaixi()20 分钟前
贪心思想之——最大子段和问题
数据结构·算法
FindYou.20 分钟前
C - Separated Lunch
算法·深度优先
ぃ扶摇ぅ25 分钟前
Windows系统编程(三)进程与线程二
c++·windows
夜雨翦春韭26 分钟前
【代码随想录Day30】贪心算法Part04
java·数据结构·算法·leetcode·贪心算法