题解:P11266 【模板】可并堆 2
Callisto_mhx · · 题解
前言
NOIP 支持 PB_DS 了!!!
pb_ds (平板电视) 也是好起来了呀。
普及:何为 pb_ds
pb_ds 是 GNU 为 C++ 提供的扩展数据结构库(注意不是 STL 哦)。
众所周知,C++ stl 中的 priority_queue
- [ ] 非堆顶删除
- [ ] 元素修改
- [ ] 直接进行合并
都做不到。
不巧,这题全要用。
这时候就要请出我们 pb_ds 库的 priority_queue 了,以上操作它都支持(喜)。
详细如下:
- 需要
bits/extc++.h头文件以及__gnu_pbds::命名空间。 - 声明:
template <
typename T, // 队列中存储的元素类型(如 int、pair<int, int>)
typename Cmp = less<T>, // 比较规则,默认 less<T> 为大根堆,greater<T> 为小根堆
typename Tag = pairing_heap_tag, // 底层实现标签(核心,决定支持的功能)
typename Alloc = std::allocator<char> // 内存分配器,默认即可,无需修改
> class priority_queue;
对比一下 stl 的:
template <
typename T, // 优先队列中存储的元素类型(必填)
typename Container = vector<T>, // 底层存储容器(可选,默认 std::vector<T>)
typename Compare = less<T> // 优先级比较规则(可选,默认 std::less<T>)
> class priority_queue;
- [x] 非堆顶删除:
q.erase(迭代器)。 - [x] 元素修改:
q.modify(迭代器, 新值)。 - [x] 直接进行合并
q1.join(q2)(将 q2 合并进 q1,同时清空 q2)。
(其他基本操作和 STL 优先队列一致)。
温馨提示:仅支持 GCC / G++ 编译器哦~(好像有 VS 人心碎了)。
好了你已经可以做这道题了(其他的见代码吧)。
code
#include <bits/stdc++.h>
#include <bits/extc++.h>
// pb_ds 库万能头文件
using namespace std;
#define endl "\n"
const int N = 1e6 + 10;
int n, m;
__gnu_pbds::priority_queue<int, greater<int> > q[N];
// 第一个参数 int:队列中存储的数据类型
// 第二个参数 greater<int>:优先级
// 第三个参数(默认):__gnu_pbds::pairing_heap_tag(配对堆)
__gnu_pbds::priority_queue<int, greater<int> >::point_iterator t[N]; // pb_ds 优先队列对应的迭代器
signed main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
cin >> n >> m;
for (int i = 1; i <= n; i++) {
int x;
cin >> x;
t[i] = q[i].push(x); // 向 q[i] 队列中插入元素 x,并将返回的迭代器存入 t[i]
}
while (m--) {
int opt, x, y, z;
cin >> opt;
if (opt == 0) {
cin >> x >> y;
q[x].erase(t[y]); // 将迭代器为 t[y] 的值删除
} else if (opt == 1) {
cin >> x;
cout << q[x].top() << endl;
} else if (opt == 2) {
cin >> x >> y;
q[x].join(q[y]); // 将 q[y] 合并进 q[x]
} else {
cin >> x >> y >> z;
q[x].modify(t[y], z); // 将迭代器为 t[y] 的值更改为 z
}
}
return 0;
}