版本比较
stl ❌ 手搓 ✅ 1
标题
增加 1 行删除 1 行
11我会排序!stl ❌ 手搓 ✅ 1正文
增加 989 行删除 8 行
1123345567789910111213141516171819202122232425262728293031323334353637383940414243444546474849505 行未改动56575859246061266263286465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009这种文章过于垃圾,所以不敢投到算法·理论了。文章过于垃圾,大家当个闲比的乱搞看就行。
## 前言# 更新日志
就是我心血来潮,想写点关于排序的东西。2026/3/15:开始写 ```Sorted``` 并出了一个题目,以测试速度。
准备手写一个排序来碾压 stl 的,大部分参考了 P4604 [WC2017] 挑战的东西。2026/3/19:开启项目。
## 排序算法发展时间表2026/3/21:写了几个普通的数据结构,于是爆掉了 ```std::unordered_map``` 并更新了 ```Unordered_map``` 然后尝试替换了几题 CF 上的卡掉我原先的 ```std::unordered_map``` 的代码,并通过,找到了一些 bug 并增加了提示。
2026/3/22:开始写 ```priority_queue``` 了。
# 前言
我发现有一些的 ```stl``` 都饱受大家的诟病?
类似于常数大的一些问题于是我打算手搓一个!
对于每一个手搓我都会评一个碾压程度,越高就比 ```stl``` 快的越多。从 $0$ 到 $10$。
**借助了 AI 工具进行梳理功能,表格总结,功能评估,卡常。**
写的过程,大概就是使用 AI 进行速度评估,让其先实现一个初版,若速度差异不大甚至已经超越 ```stl``` 的实现,故开始手搓环节,即进行卡常。
但是大部分的 ```stl``` 中的实现都是极其优秀的,例如 ```vector``` 就是一个很典型的例子。
# 一些没有实现的原因
#### vector
| 名称 | 原因 | 备注 ||:-:|:-:|:-:|| ```vector``` | 发现只有 ```push_back``` 快。 | 准备写一个 ```vector``` 专门存图用。 || ```map``` | 实现了 fhq-treap,分块,红黑树均慢 $\frac{1}{20}$,但没卡过。 | - || ```set``` | 卡不过。 | - || ```queue``` | 建议大家手写定长数组,动态扩容不一定快。 | - || ```stack``` | 建议大家手写定长数组,动态扩容不一定快。 | - || ```deque``` | 建议大家手写定长数组,动态扩容不一定快。 | - || ```bitset``` | 没有卡过,因为 ```stl``` 应该有什么汇编常数非常牛逼 | 不想使用指令集等 |
# Sorted::Sort
碾压程度:$6.5$ 分。
#### 排序算法发展时间表
不过在这之前,我们先补充一点冷知识吧!
| 时间 | 算法名称 | 发明人 || :--- | :--- | :--- |5 行未改动| 1960年 | 快速排序| 托尼·霍尔 || 1964年 | 堆排序 | J. W. J. 威廉姆斯;|| 1968年 | 双调排序 | 肯·巴彻 |
可以发现一个很有意思的事情,第一个发明的是基数排序,冒泡甚至在快排以后。这是让我没有想到的。可以发现一个很有意思的事情,第一个发明的是基数排序。
## 正题### 介绍
还在施工,咕咕咕。实现了大部分排序,对基数排序和最终的可以使用全部情况,且速度在对整形排序时与 ```std::sort``` 在不同情况下各有优劣,大家在卡常的时候可以尝试。
但是大部分是对于整形的优化,所以如果是其他的还是直接用 ```std::sort``` 就行了。缩进不太好看。
| 名称 | 速度 | 空间 | 备注 ||:-:|:-:|:-:|:-:|| ```bubble_sort``` | $\mathcal{O}(n^{2})$ | $\mathcal{O}(1)$ | - || ```insert_sort``` | $\mathcal{O}(n^{2})$ | $\mathcal{O}(1)$ | 小范围时较快 || ```selection_sort``` | $\mathcal{O}(n^{2})$ | $\mathcal{O}(1)$ | - || ```heap_sort``` | $\mathcal{O}(n \log n)$ | $\mathcal{O}(1)$ | - || ```radix_sort``` | $\mathcal{O}(n)$ | $\mathcal{O}(n)$ | 进行了大量常数优化,仅支持整形,**支持负数**,通过了 P4604 || ```merge_sort``` | $\mathcal{O}( n \log{n}) $ | $\mathcal{O}(n)$ | - || ```Sort``` | - | - | 最终版排序,通过了 P4604 |
在 ```Sort``` 中。
若整个序列位倒序,直接反转。
若大部分有序,故使用插入排序.
在 $n$ 较大同时值域大时使用基数排序。
否则使用 ```std::sort```。
调用方式与 ```std::sort``` 相同,但如果你怕重名,最好不用直接使用 ```using namespace Sorted;```
### code
:::info[全家桶 code]```cppnamespace 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``` 调用方式请注意。**
:::info[无多余函数 code]```cppnamespace 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
| 情况 | $10^{3}$ | $10^{5}$ | $10^{6}$ | $10^{7}$ ||:-:|:-:|:-:|:-:|:-:|| 乱序 | 5ms | T | T | T || 逆序 | 5ms | T | - | T || 基本有序 | 5ms | T | - | T || 排列 | 5ms | T | - | T || 顺序 | 5ms | T | - | T |
##### insert_sort
| 情况 | $10^{3}$ | $10^{5}$ | $10^{6}$ | $10^{7}$ ||:-:|:-:|:-:|:-:|:-:|| 乱序 | 4ms | T | T | T || 逆序 | 5ms | T | - | T || 基本有序 | 5ms | 6ms | - | 407ms || 排列 | 5ms | T | - | T || 顺序 | 5ms | 6ms | - | 182ms |
发自内心的说出一句牛逼。因为顺序和基本有序的情况甚至比基数排序还快。
##### selection_sort
| 情况 | $10^{3}$ | $10^{5}$ | $10^{6}$ | $10^{7}$ ||:-:|:-:|:-:|:-:|:-:|| 乱序 | 5ms | T | T | T || 逆序 | 5ms | T | - | T || 基本有序 | 5ms | T | - | T || 排列 | 5ms | T | - | T || 顺序 | 5ms | T | - | T |
##### heap_sort
| 情况 | $10^{3}$ | $10^{5}$ | $10^{6}$ | $10^{7}$ ||:-:|:-:|:-:|:-:|:-:|| 乱序 | 5ms | 158ms | T | T || 逆序 | 5ms | 11ms | - | T || 基本有序 | 5ms | 11ms | - | T || 排列 | 5ms | 13ms | - | T || 顺序 | 5ms | 11ms | - | T |
##### merge_sort
由于 ```stl::sort``` 极其优秀的实现故速度较快。
| 情况 | $10^{3}$ | $10^{5}$ | $10^{6}$ | $10^{7}$ ||:-:|:-:|:-:|:-:|:-:|| 乱序 | 5ms | 4ms | 97ms | T || 逆序 | 4ms | 8ms | - | 480ms || 基本有序 | 5ms | 8ms | - | 479ms || 排列 | 5ms | 13ms | - | **1330ms** || 顺序 | 4ms | 8ms | - | 490ms |
##### radix_sort
| 情况 | $10^{3}$ | $10^{5}$ | $10^{6}$ | $10^{7}$ ||:-:|:-:|:-:|:-:|:-:|| 乱序 | 4ms | 5ms | 50ms | 553ms || 逆序 | 5ms | 8ms | - | 583ms || 基本有序 | 5ms | 8ms | - | 582ms || 排列 | 5ms | 8ms | - | **930ms** || 顺序 | 5ms | 8ms | - | 571ms |
##### Sort
由于 ```stl::sort``` 极其优秀的实现故速度极快。
| 情况 | $10^{3}$ | $10^{5}$ | $10^{6}$ | $10^{7}$ ||:-:|:-:|:-:|:-:|:-:|| 乱序 | 4ms | 5ms | 53ms | 561ms || 逆序 | 5ms | 8ms | - | 576ms || 基本有序 | 4ms | 7ms | - | 423ms || 排列 | 5ms | 10ms | - | **1056ms** || 顺序 | 5ms | 6ms | - | 187ms |
##### std::sort
作为对照
| 情况 | $10^{3}$ | $10^{5}$ | $10^{6}$ | $10^{7}$ ||:-:|:-:|:-:|:-:|:-:|| 乱序 | 4ms | 4ms | 75ms | 814ms || 逆序 | 5ms | 7ms | - | 305ms || 基本有序 | 4ms | 7ms | - | 313ms || 排列 | 4ms | 11ms | - | **1096ms** || 顺序 | 5ms | 7ms | - | 321ms |
#### 总结/使用场景
大概率不会有 bug ,因为这么多点都测对了,但不排除。
为什么排序一个排列这么慢?
一个是因为值域小,而且每一个数字只会出现一次,导致大部分优化发挥不了作用导致的。
在序列为乱序的时候或排列显然可以使用手写的。
但是如果序列时基本有序或逆序可以使用 ```std::sort``` 但是这种情况仍是少数。
# Unodered_map
碾压程度:$3.5$ 分。
缺点很明显不支持自定义的 ```hash``` 了。
### 介绍
> 说明:复杂度按哈希表常规分析给出。> - 平均:在负载因子受控、哈希分布正常时> - 最坏:极端冲突下可能退化到 $O(n)$
**空间常数较大。**
| 函数 | 功能 | 平均复杂度 | 最坏复杂度 | 备注 ||---|---|---|---|---|| `Unordered_map()` | 默认构造,初始化最小容量 | $O(1)$ | $O(1)$ | 实际会分配初始桶数组 || `explicit Unordered_map(size_t reserve_n)` | 按预估元素数构造 | $O(m)$ | $O(m)$ | `m` 为初始桶数(初始化成本) || `Unordered_map(initializer_list<pair<K,V>> il)` | 用列表构造并插入元素 | $O(n)$ | $O(n^2)$ | 可能触发 rehash || `begin()` | 返回首个有效元素迭代器 | $O(1)$~$O(m)$ | $O(m)$ | 需跳过空桶/墓碑 || `end()` | 返回尾后迭代器 | $O(1)$ | $O(1)$ | || `begin() const` | const 版本 begin | $O(1)$~$O(m)$ | $O(m)$ | || `end() const` | const 版本 end | $O(1)$ | $O(1)$ | || `cbegin()` | const begin | $O(1)$~$O(m)$ | $O(m)$ | || `cend()` | const end | $O(1)$ | $O(1)$ | || `empty() const` | 判空 | $O(1)$ | $O(1)$ | || `size() const` | 返回元素个数 | $O(1)$ | $O(1)$ | || `bucket_count() const` | 返回桶数量 | $O(1)$ | $O(1)$ | || `load_factor() const` | 当前负载因子 | $O(1)$ | $O(1)$ | || `max_load_factor() const` | 获取最大负载因子阈值 | $O(1)$ | $O(1)$ | || `max_load_factor(float z)` | 设置最大负载因子 | $O(1)$ / $O(n)$ | $O(n)$ | 若超阈值会触发 rehash || `clear()` | 清空所有元素 | $O(m)$ | $O(m)$ | 仅重置状态,不缩容 || `reserve(size_t n)` | 预留可容纳 n 元素容量 | $O(1)$ / $O(n)$ | $O(n)$ | 需要扩容时重哈希 || `rehash(size_t n)` | 重建哈希表到新桶数 | $O(n)$ | $O(n)$ | 迁移全部有效元素 || `swap(Unordered_map& o)` | 与另一个表交换 | $O(1)$ | $O(1)$ | 向量 swap 常数级 || `count(const K& key) const` | 判断 key 是否存在(0/1) | $O(1)$ | $O(n)$ | || `contains(const K& key) const` | 判断 key 是否存在(bool) | $O(1)$ | $O(n)$ | || `find(const K& key)` | 查找 key,返回迭代器 | $O(1)$ | $O(n)$ | 找不到返回 `end()` || `find(const K& key) const` | const 查找 | $O(1)$ | $O(n)$ | || `find_ptr(const K& key)` | 查找并返回值指针 | $O(1)$ | $O(n)$ | 找不到返回 `nullptr` || `find_ptr(const K& key) const` | const 值指针查找 | $O(1)$ | $O(n)$ | || `operator[](const K& key)` | 查/插并返回 value 引用 | $O(1)$ | $O(n)$ | 不存在则插入默认值 || `at(const K& key)` | 有界访问,不存在抛异常 | $O(1)$ | $O(n)$ | || `at(const K& key) const` | const 有界访问 | $O(1)$ | $O(n)$ | || `insert(const pair<K,V>& kv)` | 插入键值对(已存在不插) | $O(1)$ | $O(n)$ | 返回 `{iterator, bool}` || `insert_or_assign(const K& key, const V& val)` | 不存在插入,存在覆盖 | $O(1)$ | $O(n)$ | 返回是否新插入 || `emplace(const K& key, Args&&...)` | 原地构造 value(已存在不插) | $O(1)$ | $O(n)$ | 返回 `{iterator, bool}` || `try_emplace(const K& key, Args&&...)` | 语义同 emplace(该实现中) | $O(1)$ | $O(n)$ | || `erase(const K& key)` | 按 key 删除 | $O(1)$ | $O(n)$ | 返回删除数量 0/1 || `erase(iterator it)` | 按迭代器删除 | $O(1)$ | $O(1)$ | 返回下一个迭代器 || `~Unordered_map()` | 析构 | $O(n)$ | $O(n)$ | 由 `vector` 释放资源 |
##### 非成员函数
| 函数 | 功能 | 平均复杂度 | 最坏复杂度 | 备注 ||---|---|---|---|---|| `swap(Unordered_map<K,V>& a, Unordered_map<K,V>& b)` | 调用成员 swap | $O(1)$ | $O(1)$ | |
##### 迭代器内部函数(通常不在外部 API 文档中)
| 函数 | 功能 | 复杂度 ||---|---|---|| `iterator::operator*()` | 解引用得到 `{const K&, V&}` | $O(1)$ || `iterator::operator++()` | 跳到下一个有效槽 | 摊还 $O(1)$,单步最坏 $O(m)$ || `const_iterator::operator*()` | 解引用得到 `{const K&, const V&}` | $O(1)$ || `const_iterator::operator++()` | 跳到下一个有效槽 | 摊还 $O(1)$,单步最坏 $O(m)$ |
使用 AI 修改了缩进的问题
### code
**注意:由于实现问题,请不要一边遍历一边修改同一个 ```map``` 哦!**
:::info[code]```cpptemplate<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);}```:::
### 测速
在 [【模板】哈希表](https://www.luogu.com.cn/problem/P11615) 完成测速。
[std::unordered_map](https://www.luogu.com.cn/record/268767092)
[Unordered_map](https://www.luogu.com.cn/record/268769670)
#### P3345 [ZJOI2015] 幻想乡战略游戏
[std::unordered_map](https://www.luogu.com.cn/record/202637581)
[Unordered_map](https://www.luogu.com.cn/record/269099834)
#### P4149 [IOI 2011] Race
[std::unordered_map](https://www.luogu.com.cn/record/199556024)
[Unordered_map](https://www.luogu.com.cn/record/269100095)
可以发现均比 ```stl``` 快。
# Priority_queue
碾压程度:$3.5$ 分。
### 介绍
**支持顶点删除某一个数字。**
实现的是二叉堆,没有选择其他堆的原因是,我不会,啊,不是,因为其他的堆的常数有点大。
| 函数 | 功能 | 时间复杂度 | 备注 ||---|---|---|---|| `sift_up(i)` | 将下标 `i` 元素上浮,恢复堆性质 | $\mathcal{O}(\log n)$ | 内部函数;常用于插入后调整 || `sift_down(i)` | 将下标 `i` 元素下沉,恢复堆性质 | $\mathcal{O}(\log n)$ | 内部函数;常用于删除后调整 || `build_heap()` | 将当前容器整体建堆 | $\mathcal{O}(n)$ | Floyd 建堆法 || `Priority_queue()` | 默认构造空堆 | $\mathcal{O}(1)$ | 默认比较器 || `Priority_queue(const Compare& compare)` | 指定比较器构造空堆 | $\mathcal{O}(1)$ | || `Priority_queue(const Compare& compare, const Container& cont)` | 拷贝容器并建堆 | $\mathcal{O}(n)$ | 拷贝 $\mathcal{O}(n)$ + 建堆 $\mathcal{O}(n)$ || `Priority_queue(const Compare& compare, Container&& cont)` | 移动容器并建堆 | $\mathcal{O}(n)$ | 建堆主导复杂度 || `Priority_queue(const Container& cont)` | 默认比较器,拷贝容器并建堆 | $\mathcal{O}(n)$ | || `Priority_queue(Container&& cont)` | 默认比较器,移动容器并建堆 | $\mathcal{O}(n)$ | || `Priority_queue(It first, It last, const Compare& compare = Compare())` | 区间构造并建堆 | $\mathcal{O}(n)$ | 区间长度记为 $n$ || `empty()` | 判断是否为空 | $\mathcal{O}(1)$ | || `size()` | 返回元素个数 | $\mathcal{O}(1)$ | || `top()` | 访问堆顶元素 | $\mathcal{O}(1)$ | 空堆时 `assert` 失败(Debug) || `push(const value_type& x)` | 拷贝插入元素 | 均摊 $\mathcal{O}(\log n)$ | 扩容时单次最坏可到 $\mathcal{O}(n)$ || `push(value_type&& x)` | 移动插入元素 | 均摊 $\mathcal{O}(\log n)$ | 同上 || `emplace(Args&&... args)` | 原地构造并插入 | 均摊 $\mathcal{O}(\log n)$ | 减少临时对象开销 || `pop()` | 删除堆顶元素 | $\mathcal{O}(\log n)$ | `size()==1` 时为 $\mathcal{O}(1)$ || `swap(Priority_queue& other)` | 交换两个堆 | 通常 $\mathcal{O}(1)$ | 取决于底层容器 `swap` || `reserve(size_type n)` | 预留容量 | 若扩容 $\mathcal{O}(n)$,否则 $\mathcal{O}(1)$ | 卡常常用 || `erase(const value_type& x)` | 删除一个值等于 `x` 的元素 | $\mathcal{O}(n)$ | 查找 $\mathcal{O}(n)$ + 调整 $\mathcal{O}(\log n)$,总为 $\mathcal{O}(n)$ || `swap(a, b)`(非成员) | 非成员交换接口 | 同成员 `swap` | 便于 `std::swap` 风格调用 |
### code
:::info[code]```cpp#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);}```:::
### 测速
#### 模板题
[Priority_queue](https://www.luogu.com.cn/record/269092856)
[std::priority_queue](https://www.luogu.com.cn/record/269092900)
#### dijkstra
[Priority_queue](https://www.luogu.com.cn/record/269096718)
[std::priority_queue](https://www.luogu.com.cn/record/269096629)
#### Johnson
[Priority_queue](https://www.luogu.com.cn/record/269097706)
[std::priority_queue](https://www.luogu.com.cn/record/259176608)
#### P2056 [ZJOI2007] 捉迷藏
[Priority_queue](https://www.luogu.com.cn/record/269099448)
[std::priority_queue](https://www.luogu.com.cn/record/269098664)
#### P3350 [ZJOI2016] 旅行者
[Priority_queue](https://www.luogu.com.cn/record/269100814)
[std::priority_queue](https://www.luogu.com.cn/record/199735127)
可以发现均比 ```stl``` 快。