堆专题3 删除堆顶元素

博客围绕堆顶删除算法展开,介绍了堆顶删除可通过取或覆盖 h[1] 实现,覆盖时将堆尾元素移到堆顶,再用向下调整操作堆,即逐级与较小(或较大)子节点比较交换,时间复杂度为 O(log n),还提及代码详解和最后提交。

题目:

样例:

输入
6
3 2 6 5 8 7

输出
7 5 6 3 2

思路:

        堆顶的删除,就是取 或者 覆盖掉 h[1],其中覆盖掉 h[1] 的操作,用向下调整操作堆即可,向下调整的过程相对简单,只需要将堆尾元素移动到堆顶,然后逐级与其较小(或较大)的子节点进行比较并交换位置。这个过程的时间复杂度是O(log n),其中n是堆中元素的数量。

即 h[1] = h[n--],downAdjust(1,n);

代码详解如下:

#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 downAdjust(int low,int high)
{
	int i = low,j = i << 1;
	
	while(j <= high)
	{
		// 如果存在右孩子,并且右孩子 更符合 堆顶 性质,那么调整 右孩子
		if(j + 1 <= high && heap[j + 1] > heap[j]) ++j;
		
		// 堆调整
		if(heap[j] > heap[i])
		{
			swap(heap[j] , heap[i]);
			i = j;
			j = i << 1;
		}else break;
	}
}

inline void DeleteTop()
{
	heap[1] = heap[n--]; // 将尾堆 覆盖堆顶
	
	downAdjust(1,n);	// 向下调整堆
}

inline void solve()
{

	cin >> n;
	
	// 插入堆
	for(int i = 1,x;i <= n;++i) cin >> heap[i];
	
	// 根据题意,向下调整堆
	for(int i = n / 2;i;--i) downAdjust(i,n);
	
	// 删除堆顶元素
	DeleteTop();
	
	// 输出堆
	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;
}

最后提交:

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值