封装堆模板

/// 主题:封装堆模板
/// 作者:GGN_2015
/// 日期:2021-04-13 

#include <cstdio>
#include <vector>
#include <cstdlib>
#include <iostream>
#include <algorithm>
using namespace std;

template<typename Type>
class Heap {
	/// 小根堆,要求类型 Type 上定义了小于号 
	
	private:
		vector<Type> vec; /// 用 vector 储存堆中的节点 
		
		void up(int pos) {
			/// 向上调整某个位置 
			while(pos > 1 && vec[pos] < vec[pos / 2]) {
				swap(vec[pos], vec[pos / 2]);
				pos /= 2;
			}
		}
		
		void down(int pos) {
			/// 向下调整某个位置 
			if(pos*2 >=  vec.size()) {
				/// 该节点没有儿子 
				return;
			}else {
				if(pos*2 + 1 >= vec.size()) {
					/// 该节点没有右子 
					if(vec[pos*2] < vec[pos]) {
						swap(vec[pos*2], vec[pos]);
					}
				}else {
					/// 该节点有两个儿子 
					int nl = pos * 2;
					int nr = pos * 2 + 1;
					if(vec[nl] < vec[pos] || vec[nr] < vec[pos]) {
						/// 需要进行调整
						if(vec[nl] < vec[nr]) {
							swap(vec[nl], vec[pos]);
							down(nl);
						}else {
							swap(vec[nr], vec[pos]);
							down(nr);
						}
					}
				}
			}
		}
	public:
		Heap() {
			/// 默认含有一个元素 
			vec.resize(1);
		}
		
		void insert(Type x) {
			/// 向堆中插入一个元素 
			
			vec.push_back(x);
			up(vec.size() - 1);
		}
		
		Type top() {
			/// 返回堆中的最大元素 
			if(vec.size() <= 1) {
				cerr << "Heap: top() when heap is empty." << endl;
				exit(-1);
			}else {
				return vec[1];
			}
		}
		
		void pop() {
			/// 删除堆中的一个最小值 
			if(vec.size() >= 2) {
				vec[1] = vec[vec.size() - 1];
				vec.pop_back();
				down(1);
			}else {
				cerr << "Heap: pop() when heap is empty." << endl;
				exit(-1);
			}
		}
		
};

Heap<int> tmp;

int main() {
	int n; scanf("%d", &n);
	while(n --) {
		int op; scanf("%d", &op);
		if(op == 1) {
			int x; scanf("%d", &x);
			tmp.insert(x);
		}else if(op == 2) {
			printf("%d\n", tmp.top());
		}else {
			tmp.pop();
		}
	}
	return 0;
}

传送门:洛谷 P3378 【模板】堆

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值