版本比较
P1177【模板】排序 题解
正文
增加 10 行删除 8 行
11234519 行未改动25262728292930313233313233343735363738393 行未改动4344454649474849505130 行未改动82838485888687888990916 行未改动9899100101102103104本题解介绍一种分块优化插入排序,时间复杂度 $\operatorname{O}(n \sqrt{n})$ 。本题解介绍一种分块优化插入排序,**平均**时间复杂度 $\operatorname{O}(n \sqrt{n\log n})$ ,**最坏**时间复杂度仍为 $\operatorname{O}(n^2)$ 。## 前置知识[插入排序](https://oi-wiki.org/basic/insertion-sort/)## 插入排序求前 $k$ 小值插入排序可以用 $\operatorname{O}(n k)$ 的复杂度求前 $k$ 小值。19 行未改动 }}```::::注意到,当 $k\le \sqrt{n}$ 时其平均时间复杂度为线性。注意到,当 $k\le \sqrt{\frac{n}{\log n}}$ 时其**平均**时间复杂度为**线性**。::::info[证明]首先,将上述代码中的 $[first,middle)$ 排序复杂度为 $\operatorname{O}(k^2)$ 。
然后,对于 $[middle,last)$ 中的每一个元素,其成为前 $k$ 小值的概率为 $\frac{k}{n}$ ,单次插入复杂度为 $\operatorname{O}(k)$ , 因此处理单个元素的复杂度为 $\operatorname{O}(\frac{k^2}{n})$ ,总复杂度为 $\operatorname{O}(n+k^2)=\operatorname{O}(n)$ 。对于第 $i$ 个元素能成为前 $i$ 个元素的前 $k$ 小值的概率为 $\frac{k}{i}$ ,插入复杂度为 $\operatorname{O}(k)$ ,比较是否是前 $k$ 小值复杂度为 $\operatorname{O}(1)$ ,因此总复杂度为 $\operatorname{O}(\sum_{1\le i\le n}(\frac{k^2}{i}+1))=\operatorname{O}(k^2\log n+n)=\operatorname{O}(n)$ 。::::但是最坏复杂度仍为 $\operatorname{O}(n k)$ ,如何优化?
将原序列打乱即可。**将原序列打乱可避免出现最坏情况。**::::info[代码]```cppmt19937 gen(random_device{}());void shuffle_insertion_partial_sort(vit first,vit mid,vit last){3 行未改动```
::::## 分块优化插入排序利用上述插入排序求前 $k$ 小值的方法,可以再$\operatorname{O}(n)$ 的时间复杂度内将原问题转化为一个长度为 $n-\sqrt{n}$ 的字问题,因此总时间复杂度为 $\operatorname{O}(n \sqrt{n})$ 。利用上述插入排序求前 $k$ 小值的方法,可以在 $\operatorname{O}(n)$ 的时间复杂度内将原问题转化为一个长度为 $n-\sqrt{\frac{n}{\log n}}$ 的子问题,因此总时间复杂度为 $\operatorname{O}(n \sqrt{n\log n})$ 。::::info[完整代码]```cpp#include<bits/stdc++.h>using namespace std; using LL=long long; using LD=long double;30 行未改动void fast_insertion_sort(vit first,vit last){ if(first==last)return; iter_swap(first,min_element(first,last)),++first; while(last-first>100){ int k=sqrt((last-first)*1.5); int n=last-first; int k=sqrt(n/log(n))*3; shuffle_insertion_partial_sort(first,first+k,last); first+=k; } insertion_sort(first,last);6 行未改动 cout<<endl;}```::::::::info[AI 使用声明]使用 AI 修正了一些错别字。::::