题目:
样例:

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