堆专题2 向上调整构建大顶堆


堆专题2 向上调整构建大顶堆

原创 于 2023-10-13 14:09:32 发布 · 粉丝可见 · 196 阅读 · 0 · 0 · 本内容遵循CC 4.0 BY-SA版权协议 版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。 GEO检测 · 编辑
文章链接:https://blog.csdn.net/hacker_51/article/details/133809056

题目:

样例:

cobol<br/>6<br/>3 2 6 5 8 7<br/>
8 6 7 2 5 3

思路:

向上调整,就是从叶子结点开始 往 根节点 往上面调整,操作与 向下调整 操作类似,只是不用判断左右孩子,由于我们是从叶子结点开始 往 根节点 往上面调整,所以不用考虑左右孩子。

代码详解如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include <iostream>
#include <vector>
#include <queue>
#include <cstring>
#include <algorithm>
#include <unordered_map>
#define endl '\n'
#define YES puts("YES")
#define NO puts("NO")
#define umap unordered_map
#define All(x) x.begin(),x.end()
#pragma GCC optimize(3,"Ofast","inline")
#define IOS std::ios::sync_with_stdio(false),cin.tie(0), cout.tie(0)
using namespace std;
const int N = 2e6 + 10;

umap<int,int>heap; // 建立堆数组
int n;

// 向上调整操作
inline void upAdjust(int low,int high)
{
int i = high,j = i >> 1; // i 为调整的孩子结点,j 为 父结点

// 如果调整的父结点在 根节点范围内
while(j >= low)
{
// 如果孩子结点比父结点大,那么向上调整
if(heap[j] < heap[i])
{
swap(heap[j] , heap[i]);
i = j;
j = i >> 1;
}else break;
}
}

// 插入堆 函数
inline void Push(int &x)
{
heap[++n] = x; // 堆尾插入结点

upAdjust(1,n); // 向上调整堆
}

inline void solve()
{
int nodeSize;
cin >> nodeSize;

// 插入堆
for(int i = 1,x;i <= nodeSize;++i) cin >> x,Push(x);

// 输出堆
for(int i = 1;i <= n;++i)
{
if(i > 1) cout << ' ';
cout << heap[i];
}
}

int main()
{
// freopen("a.txt", "r", stdin);
IOS;
int _t = 1;
// cin >> _t;
while (_t--)
{
solve();
}

return 0;
}

最后提交:


觉得不错的话,给点打赏吧 ୧(๑•̀⌄•́๑)૭

微信二维码

wechat pay

支付宝二维码

ali pay

堆专题2 向上调整构建大顶堆
http://blog.angindem.cn/2023/10/13/Angindem-CSDN博客/090_90/
作者
Angindem
发布于
2023年10月13日
许可协议