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;
}
相关推荐
迈巴赫车主11 分钟前
蓝桥杯19724食堂
java·数据结构·算法·职场和发展·蓝桥杯
6Hzlia28 分钟前
【Hot 100 刷题计划】 LeetCode 78. 子集 | C++ 回溯算法题解
c++·算法·leetcode
Kethy__31 分钟前
计算机中级-数据库系统工程师-数据结构-查找算法
数据结构·算法·软考·查找算法·计算机中级
所以遗憾是什么呢?35 分钟前
【题解】Codeforces Round 1081 (Div. 2)
数据结构·c++·算法·acm·icpc·ccpc·xcpc
白藏y1 小时前
【C++】muduo接口补充
开发语言·c++·muduo
xiaoye-duck2 小时前
《算法题讲解指南:递归,搜索与回溯算法--综合练习》--14.找出所有子集的异或总和再求和,15.全排列Ⅱ,16.电话号码的字母组合,17.括号生成
c++·算法·深度优先·回溯
OOJO2 小时前
c++---vector介绍
c语言·开发语言·数据结构·c++·算法·vim·visual studio
茉莉玫瑰花茶2 小时前
数据结构 - 并查集
数据结构
汀、人工智能2 小时前
05 - 函数基础
数据结构·算法·数据库架构·05 - 函数基础
HAPPY酷2 小时前
Python高级架构师之路——从原理到实战
java·python·算法