堆模板,自家用

本文深入探讨了C++中最小堆的数据结构实现,详细解释了堆的基本操作,包括插入元素、删除最大元素和获取堆顶元素等。通过具体代码实例,展示了如何使用模板和STL来高效地实现最小堆,为读者提供了丰富的实践经验和理论知识。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

</pre><pre name="code" class="cpp">#include <iostream>
#include <algorithm>
using namespace std;

typedef int T;
const int MAXSIZE = 1000;
struct MinHeap{
	T heap[MAXSIZE];
	int sz;
	
	MinHeap(){ sz = 0; }

	int size(){return sz; }
	
	bool empty(){ return sz==0; }
	
	void push(T val){
		heap[sz] = val;
		int pa = sz/2, cur = sz;
		while(cur>0 && heap[pa] > heap[cur]){ //push_up
			swap(heap[pa], heap[cur]);
			cur = pa;
			pa = cur/2;
		}
		sz++;
	}
	
	void pop(){
		if(empty())	return;
		heap[0] = heap[--sz];

		int tmp, tx, cur=0, lchild, rchild;
		while(cur < sz){
			lchild = 2*cur, rchild = 2*cur+1;
			tmp = heap[cur], tx = cur;
			if(lchild < sz && heap[lchild] < tmp)	tmp = heap[lchild], tx = lchild;
			if(rchild < sz && heap[rchild] < tmp)	tmp = heap[rchild], tx = rchild;
			if(tx == cur)	break; //如果孩子都比自己大,则退出
			swap(heap[tx], heap[cur]);
			cur = tx;
		}
	}
	
	T top(){
		if(empty())	return -1;
		return heap[0];
	}
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值