动态求数组中元素第k大 (pbds库 / 对顶堆)
对顶堆
todo
pbds库
使用前提
首先在头文件中加入:
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_set;
并且只能用g++编译 (clangd不可以)。
支持操作
Set
- 删除 \(x\):
ost.erase(k) - 严格小于 \(k\) 的元素数:
ost.order_of_key(k) - 集合中的第 \(k\) 个元素(从零开始计数):
ost.find_by_order(k) - \(l\) 和 \(r\) 之间的元素计数:
ost.order_of_key(r+1) – ost.order_of_key(l) - 查询元素 \(x\) 是否在序列中
cout << (ost.upper_bound(x) == ost.lower_bound(x) ? "不存在" : 存在") << '\n';
Multiset
首先将开头的 less<T> 改为 less_equal<T>
- 删除 \(x\):
ost.erase(ost.find_by_order(ost.order_of_key(x)));
其余操作一样,只不过这里的lower_bound()和upper_bound()似乎是相反的,还没有验证过。
参考资料
https://codeforces.com/blog/entry/11080
https://www.geeksforgeeks.org/ordered-set-gnu-c-pbds/
相关例题
https://codeforces.com/gym/104901/problem/K (对顶堆 / ordered_set)
https://codeforces.com/contest/1945/problem/F (可以用来测试multiset,至少用以上方法我通过了此题)

浙公网安备 33010602011771号