P3378 堆
对应章节:一、C++ 语法基础 → (十五) STL:容器、迭代器与算法。
(一) 任务与输出目标
维护插入整数、查询最小值和删除最小值三种操作。
(二) 建模与推导
默认 priority_queue 的顶端是最大值。使用 greater
(三) 手算与过程
插入 5、2 → 查询 2 → 删除 2 → 查询 5。
(四) 带注释实现
#include <bits/stdc++.h>
#define int long long
#define endl '\n'
using namespace std;
void solve() {
int n;
cin >> n;
priority_queue<int, vector<int>, greater<int>> heap;
while (n--) {
int op;
cin >> op;
if (op == 1) {
int x;
cin >> x;
heap.push(x);
}
if (op == 2)
cout << heap.top() << '\n'; // 最小元素处于堆顶。
if (op == 3)
heap.pop(); // 删除后,堆会重新选出最小元素。
}
}
signed main() {
ios::sync_with_stdio(false); // 关闭同步,使用 cin 与 cout 完成输入输出。
cin.tie(0), cout.tie(0);
int T = 1; // 本题读入一组数据。
// cin >> T; // 题目给出测试组数时开启,并在 solve 中处理一组。
while (T--)
solve();
}(五) 复杂度
插入和删除 \(O(\log n)\),查询 \(O(1)\);总时间 \(O(n\log n)\),空间 \(O(n)\)。