当前位置:网站首页>堆 AcWing 838. 堆排序
堆 AcWing 838. 堆排序
2022-07-02 09:43:00 【T_Y_F666】
堆 AcWing 838. 堆排序
原题链接
算法标签
堆
思路
堆的本质
完全二叉树
常见的堆
小根堆 根节点存储最小值, 左右节点存储值大于根节点
大根堆 根节点存储最大值, 左右节点存储值小于根节点
存储方式
采用一维数组存储 。注意: 此处数组下标从1开始
若从0开始,则根节点会被根节点左儿子覆盖
堆的基本操作
down操作 将当前节点与左右儿子比较, 若当前节点 > 左右儿子中较小值, 将当前节点与左右儿子中较小值位置交换,交换后递归进行上述操作,直至找到适合的位置
up操作 将当前节点与根节点比较, 若当前节点 < 根节点, 将当前节点与根节点位置交换,交换后递归进行上述操作,直至找到适合的位置
为了保证堆结构的稳定性,对于插入与删除操作, 选择在数组尾部进行操作
堆的基本操作伪代码
堆的构建
若依次从尾部插入,每次插入时间复杂度log(n), 需要插入n个元素, 时间复杂度n*log(n)
若依次从N/2插入,可以保证在O(n)的时间复杂度内插入n个元素
证明过程
代码
#include<bits/stdc++.h>
#define int long long
#define rep(i, a, b) for(int i=a;i<b;++i)
#define Rep(i, a, b) for(int i=a;i>b;--i)
using namespace std;
const int N = 100005;
// p存储节点祖宗节点 s存储所属连通块节点数
int a[N];
int s;
inline int read(){
int s=0,w=1;
char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')w=-1;ch=getchar();}
while(ch>='0'&&ch<='9') s=s*10+ch-'0',ch=getchar();
return s*w;
}
void put(int x) {
if(x<0) putchar('-'),x=-x;
if(x>=10) put(x/10);
putchar(x%10^48);
}
// 选取左右节点较小值
void down(int x){
int u=x;
if(x*2<=s&&a[x*2]<a[u]){
u=x*2;
}
if(x*2+1<=s&&a[x*2+1]<a[u]){
u=x*2+1;
}
if(x!=u){
swap(a[x], a[u]);
down(u);
}
}
signed main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n=read(), m=read();
s=n;
rep(i, 1, n+1){
a[i]=read();
}
Rep(i, n/2, 0){
down(i);
}
while(m--){
printf("%lld ", a[1]);
a[1]=a[s--];
down(1);
}
return 0;
}
原创不易
转载请标明出处
如果对你有所帮助 别忘啦点赞支持哈
边栏推荐
- 防抖 节流
- PR 2021 quick start tutorial, learn about the and functions of the timeline panel
- What is the relationship between NFT and metauniverse? How to view the market? The future market trend of NFT
- 计数类DP AcWing 900. 整数划分
- arcgis js 4.x 地图中加入图片
- Full link voltage measurement
- Differences between nodes and sharding in ES cluster
- Introduction to CPU instruction set
- Go learning notes - multithreading
- 寻找二叉树中任意两个数的公共祖先
猜你喜欢
随机推荐
CDH6之Sqoop添加数据库驱动
中国交通标志检测数据集
线性DP AcWing 897. 最长公共子序列
drools执行完某个规则后终止别的规则执行
async/await 异步函数
深拷贝 事件总线
LeetCode—剑指 Offer 51. 数组中的逆序对
Leetcode14 longest public prefix
The programmer and the female nurse went on a blind date and spent 360. He packed leftovers and was stunned when he received wechat at night
FBX import under ue4/ue5 runtime
考研英语二大作文模板/图表作文,英语图表作文这一篇就够了
Less than three months after the programmer was hired, the boss wanted to launch the app within one month. If he was dissatisfied, he was dismissed immediately
Win10 system OmniPeek wireless packet capturing network card driver failed to install due to digital signature problem solution
drools中then部分的写法
甜心教主:王心凌
染色法判定二分图 AcWing 860. 染色法判定二分图
Anti shake throttle
CV2 in OpenCV VideoWriter_ Fourcc() function and cv2 Combined use of videowriter() function
Post request body content cannot be retrieved repeatedly
Programmers can't find jobs after the age of 35? After reading this article, you may be able to find the answer