文章过于垃圾,大家当个闲比的乱搞看就行。
更新日志
2026/3/15:开始写 Sorted 并出了一个题目,以测试速度。
2026/3/19:开启项目。
2026/3/21:写了几个普通的数据结构,于是爆掉了 std::unordered_map 并更新了 Unordered_map 然后尝试替换了几题 CF 上的卡掉我原先的 std::unordered_map 的代码,并通过,找到了一些 bug 并增加了提示。
2026/3/22:开始写 priority_queue 了。
前言
我发现有一些的 stl 都饱受大家的诟病?
类似于常数大的一些问题于是我打算手搓一个!
对于每一个手搓我都会评一个碾压程度,越高就比 stl 快的越多。从 到 。
借助了 AI 工具进行梳理功能,表格总结,功能评估,卡常。
写的过程,大概就是使用 AI 进行速度评估,让其先实现一个初版,若速度差异不大甚至已经超越 stl 的实现,故开始手搓环节,即进行卡常。
但是大部分的 stl 中的实现都是极其优秀的,例如 vector 就是一个很典型的例子。
一些没有实现的原因
vector
| 名称 | 原因 | 备注 |
|---|---|---|
vector | 发现只有 push_back 快。 | 准备写一个 vector 专门存图用。 |
map | 实现了 fhq-treap,分块,红黑树均慢 ,但没卡过。 | - |
set | 卡不过。 | - |
queue | 建议大家手写定长数组,动态扩容不一定快。 | - |
stack | 建议大家手写定长数组,动态扩容不一定快。 | - |
deque | 建议大家手写定长数组,动态扩容不一定快。 | - |
bitset | 没有卡过,因为 stl 应该有什么汇编常数非常牛逼 | 不想使用指令集等 |
Sorted::Sort
碾压程度: 分。
排序算法发展时间表
不过在这之前,我们先补充一点冷知识吧!
| 时间 | 算法名称 | 发明人 |
|---|---|---|
| 1887年 | 基数排序 | 赫尔曼·何勒里斯 |
| 1945年 | 归并排序 | 约翰·冯·诺依曼 |
| 1954年 | 计数排序 | 哈罗德·H·苏厄德 |
| 1956年 | 冒泡排序 | 爱德华·哈里·弗兰德 |
| 1959年 | 希尔排序 | 唐纳德·L·希尔 |
| 1960年 | 快速排序 | 托尼·霍尔 |
| 1964年 | 堆排序 | J. W. J. 威廉姆斯; |
| 1968年 | 双调排序 | 肯·巴彻 |
可以发现一个很有意思的事情,第一个发明的是基数排序。
介绍
实现了大部分排序,对基数排序和最终的可以使用全部情况,且速度在对整形排序时与 std::sort 在不同情况下各有优劣,大家在卡常的时候可以尝试。
但是大部分是对于整形的优化,所以如果是其他的还是直接用 std::sort 就行了。缩进不太好看。
| 名称 | 速度 | 空间 | 备注 |
|---|---|---|---|
bubble_sort | - | ||
insert_sort | 小范围时较快 | ||
selection_sort | - | ||
heap_sort | - | ||
radix_sort | 进行了大量常数优化,仅支持整形,支持负数,通过了 P4604 | ||
merge_sort | - | ||
Sort | - | - | 最终版排序,通过了 P4604 |
在 Sort 中。
若整个序列位倒序,直接反转。
若大部分有序,故使用插入排序.
在 较大同时值域大时使用基数排序。
否则使用 std::sort。
调用方式与 std::sort 相同,但如果你怕重名,最好不用直接使用 using namespace Sorted;
code
全家桶 code
namespace Sorted{
template<typename T>
static inline T* new_aligned(int n, int align = 64) {
size_t total = n * sizeof(T) + align;
char* raw = new char[total];
size_t addr = reinterpret_cast<size_t>(raw);
size_t offset = (align - addr % align) % align;
return reinterpret_cast<T*>(raw + offset);
}
template<typename T>
static inline void delete_aligned(T* ptr) {
delete[] reinterpret_cast<char*>(ptr);
}
template<typename T>static inline void Swap(T&x,T&y){
T t=x;x=y;y=t;
}
// 冒泡排序
namespace bubble_sort{
template<typename T>static inline void sort(T* fr,T* to){
if(fr==to)return ;
int n=static_cast<int>(to-fr)-2;
for(int i=0;i<=n;i=-~i)for(int j=0;j<=n-i;j=-~j)
if(fr[j]>fr[j+1])Swap(fr[j],fr[j+1]);
}
}
// 插入排序
namespace insert_sort{
template<typename T>static inline void sort(T* fr,T* to){
if(fr==to)return ;
for(T* i=fr+1;i!=to;i++)for(T* j=i;j!=fr;j--)
if(*(j-1)>*j)Swap(*(j-1),*j);else break;
}
}
// 选择排序
namespace selection_sort{
template<typename T>static inline void sort(T* fr,T* to){
if(fr==to)return ;
for(T* i=fr;i!=to-1;i++){
T* Mnpos=i;
for(T* j=i+1;j!=to;j++)if(*j<*Mnpos)Mnpos=j;
if(i!=Mnpos)Swap(*i,*Mnpos);
}
}
}
// 堆排序
namespace heap_sort{
template<typename T>static inline void PushDown(T* a,int root,int n){
while(true){
int lchild=(root<<1)+1,rchild=(root<<1)+2,mxpos=root;
if(lchild<n&&a[lchild]>a[mxpos])mxpos=lchild;
if(rchild<n&&a[rchild]>a[mxpos])mxpos=rchild;
if(mxpos==root)break;
Swap(a[root],a[mxpos]);
root=mxpos;
}
}
template<typename T>static inline void sort(T* fr,T* to){
int n=to-fr;
if(n<=1)return ;
for(int i=n/2-1;i>=0;i=~-i)PushDown(fr,i,n);
for(int i=n-1;i>=1;i=~-i)Swap(fr[0],fr[i]),PushDown(fr,0,i);
}
}
// 神の基♂数排序
namespace radix_sort{
unsigned int cnt[2048] __attribute__((aligned(64)));
template<typename T>static inline void sort(T* fr,T* to){
if(fr==to)return ;
using UT=typename make_unsigned<T>::type;
int n=static_cast<int>(to-fr);
constexpr int PASS=sizeof(T);
constexpr int B=11;
int MASK=(1<<B)-1;
constexpr UT SIGN_MASK=UT(1)<<(PASS*8-1);
if(n<=1)return ;
T* b=new_aligned<T>(n);
int i,shift;
constexpr int MAX_PASS=(PASS*8+B-1)/B;
for(int p=0;p<MAX_PASS;p=-~p){
MASK=(1<<(min(B,PASS*8-p*B)))-1;
for(i=0;i<=MASK;i=-~i)cnt[i]=0;
shift=p*B;
for(i=0;i^n;i=-~i){
UT x=static_cast<UT>(fr[i]);
if(is_signed<T>::value)x^=SIGN_MASK;
cnt[(x>>shift)&MASK]=-~cnt[(x>>shift)&MASK];
}
for(i=1;i<=MASK;i=-~i)cnt[i]+=cnt[i-1];
for(i=n-1;~i;i=~-i){
UT x=static_cast<UT>(fr[i]);
if(is_signed<T>::value)x^=SIGN_MASK;
b[--cnt[(x>>shift)&MASK]]=fr[i];
}
Swap(fr,b);
}
if(MAX_PASS&1)memcpy(to-n,fr,n*sizeof(T));
}
}
// 归并排序
namespace merge_sort{
int Sqrn=0;
template<typename T>static inline void merge(T* fr,T* mid,T* to,T* b){
T* l=fr;
T* r=mid;
T* p=b;
while(l<mid&&r<to)*p++=(*l<=*r)?(*l++):(*r++);
while(l<mid)*p++=*l++;while(r<to)*p++=*r++;
for(T* i=fr;i!=to;i++)*i=b[i-fr];
}
template<typename T>static inline void Merge_Sort(T* fr,T* to,T* b){
int n=static_cast<int>(to-fr);
if(n<=1)return ;
if(n<=Sqrn)return static_cast<void>(sort(fr,to));
T* mid=fr+(n>>1);
Merge_Sort(fr,mid,b);
Merge_Sort(mid,to,b);
merge(fr,mid,to,b);
}
template<typename T>static inline void sort(T* fr,T* to){
int n=static_cast<int>(to-fr);
if(n<=1)return ;
Sqrn=static_cast<int>(sqrt(n));
T* b=new T[n];
Merge_Sort(fr,to,b);
delete[] b;
}
}
namespace Sort{
#define Max(x,y) ((x)>(y)?(x):(y))
template<typename T>static inline void sort(T* fr,T* to){
int n=static_cast<int>(to-fr);
if(n<=1)return ;
if(n<=64)return static_cast<void>(insert_sort::sort(fr,to));
int bad=0;
T mx=fr[0];
for(int i=1;i^n;i=-~i,mx=Max(mx,fr[i]))
if(fr[i-1]>fr[i])bad=-~bad;
if(bad==n-1)return static_cast<void>(reverse(fr,to));
if(bad<300)return static_cast<void>(insert_sort::sort(fr,to));
if(is_integral<T>::value&&(n>=10000||(bad<<1)>n)&&mx>(n<<4))
return static_cast<void>(radix_sort::sort(fr,to));
std::sort(fr,to);
}
}
}上下两版的 Sort 调用方式请注意。
无多余函数 code
namespace Sorted{
template<typename T>
static inline T* new_aligned(int n, int align = 64) {
size_t total = n * sizeof(T) + align;
char* raw = new char[total];
size_t addr = reinterpret_cast<size_t>(raw);
size_t offset = (align - addr % align) % align;
return reinterpret_cast<T*>(raw + offset);
}
template<typename T>static inline void Swap(T&x,T&y){
T t=x;x=y;y=t;
}
namespace insert_sort{
template<typename T>static inline void sort(T* fr,T* to){
if(fr==to)return ;
for(T* i=fr+1;i!=to;i++)for(T* j=i;j!=fr;j--)
if(*(j-1)>*j)Swap(*(j-1),*j);else break;
}
}
namespace radix_sort{
unsigned int cnt[2048] __attribute__((aligned(64)));
template<typename T>static inline void sort(T* fr,T* to){
if(fr==to)return ;
using UT=typename make_unsigned<T>::type;
int n=static_cast<int>(to-fr);
constexpr int PASS=sizeof(T);
constexpr int B=11;
int MASK=(1<<B)-1;
constexpr UT SIGN_MASK=UT(1)<<(PASS*8-1);
if(n<=1)return ;
T* b=new_aligned<T>(n);
int i,shift;
constexpr int MAX_PASS=(PASS*8+B-1)/B;
for(int p=0;p<MAX_PASS;p=-~p){
MASK=(1<<(min(B,PASS*8-p*B)))-1;
for(i=0;i<=MASK;i=-~i)cnt[i]=0;
shift=p*B;
for(i=0;i^n;i=-~i){
UT x=static_cast<UT>(fr[i]);
if(is_signed<T>::value)x^=SIGN_MASK;
cnt[(x>>shift)&MASK]=-~cnt[(x>>shift)&MASK];
}
for(i=1;i<=MASK;i=-~i)cnt[i]+=cnt[i-1];
for(i=n-1;~i;i=~-i){
UT x=static_cast<UT>(fr[i]);
if(is_signed<T>::value)x^=SIGN_MASK;
b[--cnt[(x>>shift)&MASK]]=fr[i];
}
Swap(fr,b);
}
if(MAX_PASS&1)memcpy(to-n,fr,n*sizeof(T));
}
}
#define Max(x,y) ((x)>(y)?(x):(y))
template<typename T>static inline void sort(T* fr,T* to){
int n=static_cast<int>(to-fr);
if(n<=1)return ;
if(n<=64)return static_cast<void>(insert_sort::sort(fr,to));
int bad=0;
T mx=fr[0];
for(int i=1;i^n;i=-~i,mx=Max(mx,fr[i]))
if(fr[i-1]>fr[i])bad=-~bad;
if(bad==n-1)return static_cast<void>(reverse(fr,to));
if(bad<300)return static_cast<void>(insert_sort::sort(fr,to));
if(is_integral<T>::value&&(n>=10000||(bad<<1)>n)&&mx>(n<<4))
return static_cast<void>(radix_sort::sort(fr,to));
std::sort(fr,to);
}
#undef Max
}在使用时如果报错了,可能需要删除 sort 前面的 static 哦。
如果要使用最终版排序直接 Sorted::Sort 即可,其他的需要打 Sorted::radix_sort::sort 的方式。
测速
在 https://www.luogu.com.cn/problem/U669872 与 P4604 完成测速。取平均数计算,其中 T 代表超时。
bubble_sort
| 情况 | ||||
|---|---|---|---|---|
| 乱序 | 5ms | T | T | T |
| 逆序 | 5ms | T | - | T |
| 基本有序 | 5ms | T | - | T |
| 排列 | 5ms | T | - | T |
| 顺序 | 5ms | T | - | T |
insert_sort
| 情况 | ||||
|---|---|---|---|---|
| 乱序 | 4ms | T | T | T |
| 逆序 | 5ms | T | - | T |
| 基本有序 | 5ms | 6ms | - | 407ms |
| 排列 | 5ms | T | - | T |
| 顺序 | 5ms | 6ms | - | 182ms |
发自内心的说出一句牛逼。因为顺序和基本有序的情况甚至比基数排序还快。
selection_sort
| 情况 | ||||
|---|---|---|---|---|
| 乱序 | 5ms | T | T | T |
| 逆序 | 5ms | T | - | T |
| 基本有序 | 5ms | T | - | T |
| 排列 | 5ms | T | - | T |
| 顺序 | 5ms | T | - | T |
heap_sort
| 情况 | ||||
|---|---|---|---|---|
| 乱序 | 5ms | 158ms | T | T |
| 逆序 | 5ms | 11ms | - | T |
| 基本有序 | 5ms | 11ms | - | T |
| 排列 | 5ms | 13ms | - | T |
| 顺序 | 5ms | 11ms | - | T |
merge_sort
由于 stl::sort 极其优秀的实现故速度较快。
| 情况 | ||||
|---|---|---|---|---|
| 乱序 | 5ms | 4ms | 97ms | T |
| 逆序 | 4ms | 8ms | - | 480ms |
| 基本有序 | 5ms | 8ms | - | 479ms |
| 排列 | 5ms | 13ms | - | 1330ms |
| 顺序 | 4ms | 8ms | - | 490ms |
radix_sort
| 情况 | ||||
|---|---|---|---|---|
| 乱序 | 4ms | 5ms | 50ms | 553ms |
| 逆序 | 5ms | 8ms | - | 583ms |
| 基本有序 | 5ms | 8ms | - | 582ms |
| 排列 | 5ms | 8ms | - | 930ms |
| 顺序 | 5ms | 8ms | - | 571ms |
Sort
由于 stl::sort 极其优秀的实现故速度极快。
| 情况 | ||||
|---|---|---|---|---|
| 乱序 | 4ms | 5ms | 53ms | 561ms |
| 逆序 | 5ms | 8ms | - | 576ms |
| 基本有序 | 4ms | 7ms | - | 423ms |
| 排列 | 5ms | 10ms | - | 1056ms |
| 顺序 | 5ms | 6ms | - | 187ms |
std::sort
作为对照
| 情况 | ||||
|---|---|---|---|---|
| 乱序 | 4ms | 4ms | 75ms | 814ms |
| 逆序 | 5ms | 7ms | - | 305ms |
| 基本有序 | 4ms | 7ms | - | 313ms |
| 排列 | 4ms | 11ms | - | 1096ms |
| 顺序 | 5ms | 7ms | - | 321ms |
总结/使用场景
大概率不会有 bug ,因为这么多点都测对了,但不排除。
为什么排序一个排列这么慢?
一个是因为值域小,而且每一个数字只会出现一次,导致大部分优化发挥不了作用导致的。
在序列为乱序的时候或排列显然可以使用手写的。
但是如果序列时基本有序或逆序可以使用 std::sort 但是这种情况仍是少数。
Unodered_map
碾压程度: 分。
缺点很明显不支持自定义的 hash 了。
介绍
说明:复杂度按哈希表常规分析给出。
- 平均:在负载因子受控、哈希分布正常时
- 最坏:极端冲突下可能退化到
空间常数较大。
| 函数 | 功能 | 平均复杂度 | 最坏复杂度 | 备注 |
|---|---|---|---|---|
Unordered_map() | 默认构造,初始化最小容量 | 实际会分配初始桶数组 | ||
explicit Unordered_map(size_t reserve_n) | 按预估元素数构造 | m 为初始桶数(初始化成本) | ||
Unordered_map(initializer_list<pair<K,V>> il) | 用列表构造并插入元素 | 可能触发 rehash | ||
begin() | 返回首个有效元素迭代器 | ~ | 需跳过空桶/墓碑 | |
end() | 返回尾后迭代器 | |||
begin() const | const 版本 begin | ~ | ||
end() const | const 版本 end | |||
cbegin() | const begin | ~ | ||
cend() | const end | |||
empty() const | 判空 | |||
size() const | 返回元素个数 | |||
bucket_count() const | 返回桶数量 | |||
load_factor() const | 当前负载因子 | |||
max_load_factor() const | 获取最大负载因子阈值 | |||
max_load_factor(float z) | 设置最大负载因子 | / | 若超阈值会触发 rehash | |
clear() | 清空所有元素 | 仅重置状态,不缩容 | ||
reserve(size_t n) | 预留可容纳 n 元素容量 | / | 需要扩容时重哈希 | |
rehash(size_t n) | 重建哈希表到新桶数 | 迁移全部有效元素 | ||
swap(Unordered_map& o) | 与另一个表交换 | 向量 swap 常数级 | ||
count(const K& key) const | 判断 key 是否存在(0/1) | |||
contains(const K& key) const | 判断 key 是否存在(bool) | |||
find(const K& key) | 查找 key,返回迭代器 | 找不到返回 end() | ||
find(const K& key) const | const 查找 | |||
find_ptr(const K& key) | 查找并返回值指针 | 找不到返回 nullptr | ||
find_ptr(const K& key) const | const 值指针查找 | |||
operator[](const K& key) | 查/插并返回 value 引用 | 不存在则插入默认值 | ||
at(const K& key) | 有界访问,不存在抛异常 | |||
at(const K& key) const | const 有界访问 | |||
insert(const pair<K,V>& kv) | 插入键值对(已存在不插) | 返回 {iterator, bool} | ||
insert_or_assign(const K& key, const V& val) | 不存在插入,存在覆盖 | 返回是否新插入 | ||
emplace(const K& key, Args&&...) | 原地构造 value(已存在不插) | 返回 {iterator, bool} | ||
try_emplace(const K& key, Args&&...) | 语义同 emplace(该实现中) | |||
erase(const K& key) | 按 key 删除 | 返回删除数量 0/1 | ||
erase(iterator it) | 按迭代器删除 | 返回下一个迭代器 | ||
~Unordered_map() | 析构 | 由 vector 释放资源 |
非成员函数
| 函数 | 功能 | 平均复杂度 | 最坏复杂度 | 备注 |
|---|---|---|---|---|
swap(Unordered_map<K,V>& a, Unordered_map<K,V>& b) | 调用成员 swap |
迭代器内部函数(通常不在外部 API 文档中)
| 函数 | 功能 | 复杂度 |
|---|---|---|
iterator::operator*() | 解引用得到 {const K&, V&} | |
iterator::operator++() | 跳到下一个有效槽 | 摊还 ,单步最坏 |
const_iterator::operator*() | 解引用得到 {const K&, const V&} | |
const_iterator::operator++() | 跳到下一个有效槽 | 摊还 ,单步最坏 |
使用 AI 修改了缩进的问题
code
注意:由于实现问题,请不要一边遍历一边修改同一个 map 哦!
code
template<class K, class V>
class Unordered_map {
static_assert(std::is_integral<K>::value,
"Unordered_map super-fast mode requires integral K.");
private:
struct Node {
K k;
V v;
};
std::vector<Node> tab_;
std::vector<unsigned char> st_;
std::size_t mask_;
std::size_t sz_;
std::size_t used_;
float max_lf_;
static inline uint64_t splitmix64(uint64_t x) {
x += 0x9e3779b97f4a7c15ULL;
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9ULL;
x = (x ^ (x >> 27)) * 0x94d049bb133111ebULL;
return x ^ (x >> 31);
}
static inline std::size_t ceil_pow2(std::size_t x) {
std::size_t n = 1;
while (n < x) n <<= 1;
return n;
}
inline std::size_t hash_key(const K& key) const {
return (std::size_t)splitmix64((uint64_t)key) & mask_;
}
inline void init_pow2(std::size_t cap) {
std::size_t n = ceil_pow2(cap < 8 ? 8 : cap);
tab_.assign(n, Node());
st_.assign(n, 0);
mask_ = n - 1;
sz_ = 0;
used_ = 0;
}
inline std::size_t find_slot(const K& key) const {
std::size_t i = hash_key(key);
std::size_t first_del = (std::size_t)-1;
while (true) {
unsigned char s = st_[i];
if (s == 0) return (first_del == (std::size_t)-1 ? i : first_del);
if (s == 1 && tab_[i].k == key) return i;
if (s == 2 && first_del == (std::size_t)-1) first_del = i;
i = (i + 1) & mask_;
}
}
inline std::size_t find_existing_slot(const K& key) const {
std::size_t i = hash_key(key);
while (true) {
unsigned char s = st_[i];
if (s == 0) return (std::size_t)-1;
if (s == 1 && tab_[i].k == key) return i;
i = (i + 1) & mask_;
}
}
inline void maybe_rebuild_before_insert() {
if (tab_.empty()) init_pow2(8);
if ((float)(used_ + 1) > (float)tab_.size() * max_lf_) {
rehash(tab_.size() << 1);
return;
}
if (used_ > sz_ + (sz_ >> 1) && tab_.size() >= 64) {
rehash(tab_.size());
}
}
public:
class iterator {
friend class Unordered_map;
Unordered_map* mp_;
std::size_t i_;
inline void skip_to_full() {
while (i_ < mp_->tab_.size() && mp_->st_[i_] != 1) ++i_;
}
inline iterator(Unordered_map* mp, std::size_t i) : mp_(mp), i_(i) {
if (mp_) skip_to_full();
}
public:
typedef std::forward_iterator_tag iterator_category;
typedef std::pair<const K, V> value_type;
typedef std::ptrdiff_t difference_type;
inline iterator() : mp_(0), i_(0) {}
inline std::pair<const K&, V&> operator*() const {
return std::pair<const K&, V&>(mp_->tab_[i_].k, mp_->tab_[i_].v);
}
inline iterator& operator++() {
++i_; skip_to_full();
return *this;
}
inline bool operator==(const iterator& o) const { return mp_ == o.mp_ && i_ == o.i_; }
inline bool operator!=(const iterator& o) const { return !(*this == o); }
inline std::size_t index() const { return i_; }
};
class const_iterator {
friend class Unordered_map;
const Unordered_map* mp_;
std::size_t i_;
inline void skip_to_full() {
while (i_ < mp_->tab_.size() && mp_->st_[i_] != 1) ++i_;
}
inline const_iterator(const Unordered_map* mp, std::size_t i) : mp_(mp), i_(i) {
if (mp_) skip_to_full();
}
public:
typedef std::forward_iterator_tag iterator_category;
typedef std::pair<const K, const V> value_type;
typedef std::ptrdiff_t difference_type;
inline const_iterator() : mp_(0), i_(0) {}
inline std::pair<const K&, const V&> operator*() const {
return std::pair<const K&, const V&>(mp_->tab_[i_].k, mp_->tab_[i_].v);
}inline const_iterator& operator++() {
++i_; skip_to_full();
return *this;
}inline bool operator==(const const_iterator& o) const { return mp_ == o.mp_ && i_ == o.i_; }
inline bool operator!=(const const_iterator& o) const { return !(*this == o); }
inline std::size_t index() const { return i_; }
};inline Unordered_map() : mask_(0), sz_(0), used_(0), max_lf_(0.70f) {
init_pow2(8);
}inline explicit Unordered_map(std::size_t reserve_n) : mask_(0), sz_(0), used_(0), max_lf_(0.70f) {
std::size_t cap = 8;
while ((float)cap * max_lf_ < (float)reserve_n) cap <<= 1;
init_pow2(cap);
}inline Unordered_map(std::initializer_list<std::pair<K, V> > il)
: mask_(0), sz_(0), used_(0), max_lf_(0.70f) {
std::size_t cap = 8;
while ((float)cap * max_lf_ < (float)il.size()) cap <<= 1;
init_pow2(cap);
for (typename std::initializer_list<std::pair<K, V> >::const_iterator it = il.begin(); it != il.end(); ++it) {
insert_or_assign(it->first, it->second);
}
}inline iterator begin() { return iterator(this, 0); }
inline iterator end() { return iterator(this, tab_.size()); }
inline const_iterator begin() const { return const_iterator(this, 0); }
inline const_iterator end() const { return const_iterator(this, tab_.size()); }
inline const_iterator cbegin() const { return const_iterator(this, 0); }
inline const_iterator cend() const { return const_iterator(this, tab_.size()); }
inline bool empty() const { return sz_ == 0; }
inline std::size_t size() const { return sz_; }
inline std::size_t bucket_count() const { return tab_.size(); }
inline float load_factor() const {
return tab_.empty() ? 0.0f : (float)sz_ / (float)tab_.size();
}inline float max_load_factor() const { return max_lf_; }
inline void max_load_factor(float z) {
if (z <= 0.1f) z = 0.1f;
if (z >= 0.95f) z = 0.95f;
max_lf_ = z;
if (load_factor() > max_lf_) rehash(tab_.size() << 1);
}inline void clear() {
std::fill(st_.begin(), st_.end(), (unsigned char)0);
sz_ = 0;
used_ = 0;
}inline void reserve(std::size_t n) {
std::size_t cap = 8;
while ((float)cap * max_lf_ < (float)n) cap <<= 1;
if (cap > tab_.size()) rehash(cap);
}void rehash(std::size_t n) {
std::vector<Node> old_tab;
std::vector<unsigned char> old_st;
old_tab.swap(tab_);
old_st.swap(st_);
init_pow2(n);
for (std::size_t i = 0; i < old_tab.size(); ++i) {
if (old_st[i] == 1) {
insert_or_assign(old_tab[i].k, old_tab[i].v);
}
}
}inline void swap(Unordered_map& o) {
tab_.swap(o.tab_);
st_.swap(o.st_);
std::swap(mask_, o.mask_);
std::swap(sz_, o.sz_);
std::swap(used_, o.used_);
std::swap(max_lf_, o.max_lf_);
}inline std::size_t count(const K& key) const {
return find_existing_slot(key) == (std::size_t)-1 ? 0u : 1u;
}inline bool contains(const K& key) const {
return find_existing_slot(key) != (std::size_t)-1;
}inline iterator find(const K& key) {
std::size_t p = find_existing_slot(key);
return (p == (std::size_t)-1) ? end() : iterator(this, p);
}inline const_iterator find(const K& key) const {
std::size_t p = find_existing_slot(key);
return (p == (std::size_t)-1) ? end() : const_iterator(this, p);
}inline V* find_ptr(const K& key) {
std::size_t p = find_existing_slot(key);
return (p == (std::size_t)-1) ? 0 : &tab_[p].v;
}inline const V* find_ptr(const K& key) const {
std::size_t p = find_existing_slot(key);
return (p == (std::size_t)-1) ? 0 : &tab_[p].v;
}inline V& operator[](const K& key) {
maybe_rebuild_before_insert();
std::size_t p = find_slot(key);
if (st_[p] != 1) {
if (st_[p] == 0) ++used_;
st_[p] = 1;
tab_[p].k = key;
tab_[p].v = V();
++sz_;
}
return tab_[p].v;
}
inline V& at(const K& key) {
std::size_t p = find_existing_slot(key);
if (p == (std::size_t)-1) throw std::out_of_range("Unordered_map::at");
return tab_[p].v;
}
inline const V& at(const K& key) const {
std::size_t p = find_existing_slot(key);
if (p == (std::size_t)-1) throw std::out_of_range("Unordered_map::at");
return tab_[p].v;
}
inline std::pair<iterator, bool> insert(const std::pair<K, V>& kv) {
maybe_rebuild_before_insert();
std::size_t p = find_slot(kv.first);
if (st_[p] == 1) return std::make_pair(iterator(this, p), false);
if (st_[p] == 0) ++used_;
st_[p] = 1;
tab_[p].k = kv.first;
tab_[p].v = kv.second;
++sz_;
return std::make_pair(iterator(this, p), true);
}
inline bool insert_or_assign(const K& key, const V& val) {
maybe_rebuild_before_insert();
std::size_t p = find_slot(key);
if (st_[p] == 1) {
tab_[p].v = val;
return false;
}
if (st_[p] == 0) ++used_;
st_[p] = 1;
tab_[p].k = key;
tab_[p].v = val;
++sz_;
return true;
}
template<class... Args>
inline std::pair<iterator, bool> emplace(const K& key, Args&&... args) {
maybe_rebuild_before_insert();
std::size_t p = find_slot(key);
if (st_[p] == 1) return std::make_pair(iterator(this, p), false);
if (st_[p] == 0) ++used_;
st_[p] = 1;
tab_[p].k = key;
tab_[p].v = V(std::forward<Args>(args)...);
++sz_;
return std::make_pair(iterator(this, p), true);
}
template<class... Args>
inline std::pair<iterator, bool> try_emplace(const K& key, Args&&... args) {
return emplace(key, std::forward<Args>(args)...);
}
inline std::size_t erase(const K& key) {
std::size_t p = find_existing_slot(key);
if (p == (std::size_t)-1) return 0;
st_[p] = 2;
--sz_;
return 1;
}
inline iterator erase(iterator it) {
if (it == end()) return end();
std::size_t p = it.index();
st_[p] = 2;
--sz_;
++it;
return it;
}
};
template<class K, class V>
inline void swap(Unordered_map<K, V>& a, Unordered_map<K, V>& b) {
a.swap(b);
}测速
在 【模板】哈希表 完成测速。
P3345 [ZJOI2015] 幻想乡战略游戏
P4149 [IOI 2011] Race
可以发现均比 stl 快。
Priority_queue
碾压程度: 分。
介绍
支持顶点删除某一个数字。
实现的是二叉堆,没有选择其他堆的原因是,我不会,啊,不是,因为其他的堆的常数有点大。
| 函数 | 功能 | 时间复杂度 | 备注 |
|---|---|---|---|
sift_up(i) | 将下标 i 元素上浮,恢复堆性质 | 内部函数;常用于插入后调整 | |
sift_down(i) | 将下标 i 元素下沉,恢复堆性质 | 内部函数;常用于删除后调整 | |
build_heap() | 将当前容器整体建堆 | Floyd 建堆法 | |
Priority_queue() | 默认构造空堆 | 默认比较器 | |
Priority_queue(const Compare& compare) | 指定比较器构造空堆 | ||
Priority_queue(const Compare& compare, const Container& cont) | 拷贝容器并建堆 | 拷贝 + 建堆 | |
Priority_queue(const Compare& compare, Container&& cont) | 移动容器并建堆 | 建堆主导复杂度 | |
Priority_queue(const Container& cont) | 默认比较器,拷贝容器并建堆 | ||
Priority_queue(Container&& cont) | 默认比较器,移动容器并建堆 | ||
Priority_queue(It first, It last, const Compare& compare = Compare()) | 区间构造并建堆 | 区间长度记为 | |
empty() | 判断是否为空 | ||
size() | 返回元素个数 | ||
top() | 访问堆顶元素 | 空堆时 assert 失败(Debug) | |
push(const value_type& x) | 拷贝插入元素 | 均摊 | 扩容时单次最坏可到 |
push(value_type&& x) | 移动插入元素 | 均摊 | 同上 |
emplace(Args&&... args) | 原地构造并插入 | 均摊 | 减少临时对象开销 |
pop() | 删除堆顶元素 | size()==1 时为 | |
swap(Priority_queue& other) | 交换两个堆 | 通常 | 取决于底层容器 swap |
reserve(size_type n) | 预留容量 | 若扩容 ,否则 | 卡常常用 |
erase(const value_type& x) | 删除一个值等于 x 的元素 | 查找 + 调整 ,总为 | |
swap(a, b)(非成员) | 非成员交换接口 | 同成员 swap | 便于 std::swap 风格调用 |
code
code
#include <vector>
#include <functional>
#include <utility>
#include <cassert>
template <class T, class Container = std::vector<T>, class Compare = std::less<T>>
class Priority_queue {
public:
using value_type = T;
using container_type = Container;
using value_compare = Compare;
using size_type = typename Container::size_type;
using const_reference = const value_type&;
private:
Container c;
Compare comp;
inline void sift_up(size_type i) {
value_type v = std::move(c[i]);
while (i) {
size_type p = (i - 1) >> 1;
if (!comp(c[p], v)) break;
c[i] = std::move(c[p]);
i = p;
}
c[i] = std::move(v);
}
inline void sift_down(size_type i) {
const size_type n = c.size();
value_type v = std::move(c[i]);
while (true) {
size_type l = (i << 1) + 1;
if (l >= n) break;
size_type r = l + 1;
size_type best = (r < n && comp(c[l], c[r])) ? r : l;
if (!comp(v, c[best])) break;
c[i] = std::move(c[best]);
i = best;
}
c[i] = std::move(v);
}
inline void build_heap() {
if (c.empty()) return;
for (size_type i = c.size() / 2; i-- > 0;)
sift_down(i);
}
public:
Priority_queue() = default;
explicit Priority_queue(const Compare& compare)
: c(), comp(compare) {}
Priority_queue(const Compare& compare, const Container& cont)
: c(cont), comp(compare) {
build_heap();
}
Priority_queue(const Compare& compare, Container&& cont)
: c(std::move(cont)), comp(compare) {
build_heap();
}
explicit Priority_queue(const Container& cont)
: c(cont), comp() {
build_heap();
}
explicit Priority_queue(Container&& cont)
: c(std::move(cont)), comp() {
build_heap();
}
template <class It>
Priority_queue(It first, It last, const Compare& compare = Compare())
: c(first, last), comp(compare) {
build_heap();
}
[[nodiscard]] inline bool empty() const noexcept {
return c.empty();
}
[[nodiscard]] inline size_type size() const noexcept {
return c.size();
}
inline const_reference top() const {
assert(!c.empty());
return c.front();
}
inline void push(const value_type& x) {
c.push_back(x);
sift_up(c.size() - 1);
}
inline void push(value_type&& x) {
c.push_back(std::move(x));
sift_up(c.size() - 1);
}
template <class... Args>
inline void emplace(Args&&... args) {
c.emplace_back(std::forward<Args>(args)...);
sift_up(c.size() - 1);
}
inline void pop() {
assert(!c.empty());
if (c.size() == 1) {
c.pop_back();
return;
}
c.front() = std::move(c.back());
c.pop_back();
sift_down(0);
}
inline void swap(Priority_queue& other) noexcept(
noexcept(std::swap(c, other.c)) && noexcept(std::swap(comp, other.comp))) {
using std::swap;
swap(c, other.c);
swap(comp, other.comp);
}
inline void reserve(size_type n) {c.reserve(n);}
inline bool erase(const value_type& x) {
for (size_type i = 0; i < c.size(); ++i) {
if (c[i] == x) {
const size_type last = c.size() - 1;
if (i == last) {
c.pop_back();
return true;
}
c[i] = std::move(c.back());
c.pop_back();
if (i > 0 && comp(c[(i - 1) >> 1], c[i]))
sift_up(i);
else
sift_down(i);
return true;
}
}
return false;
}
};
template <class T, class Container, class Compare>
inline void swap(Priority_queue<T, Container, Compare>& a,
Priority_queue<T, Container, Compare>& b) noexcept(noexcept(a.swap(b))) {
a.swap(b);
}测速
模板题
dijkstra
Johnson
P2056 [ZJOI2007] 捉迷藏
P3350 [ZJOI2016] 旅行者
可以发现均比 stl 快。