/// 主题:封装堆模板
/// 作者: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 【模板】堆