堆专题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/> |

思路:
向上调整,就是从叶子结点开始 往 根节点 往上面调整,操作与 向下调整 操作类似,只是不用判断左右孩子,由于我们是从叶子结点开始 往 根节点 往上面调整,所以不用考虑左右孩子。
代码详解如下:
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; 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() {
IOS; int _t = 1;
while (_t--) { solve(); } return 0; }
|
最后提交:
