跳到正文

个人记录

ZLR发明的一些奇奇怪怪的算法(待更新)

__biu_biu_biu__约 3 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年5月23日
篇幅
约 3 分钟

版本

  1. v1当前

1.分块优化排序

不仅有着比 sort 更慢的速度,还比 sort 难写,核心思路是将序列分成 MM 块,每块进行 nMlog⁡nM\frac{n}{M} \log{\frac{n}{M}} 时间的排序后,在进行多路归并(使用 priority_queue 解决,由于序列中最多存在 MM 个元素,所以 priority_queue 单次的最高复杂度为 log⁡nM\log{\frac{n}{M}},共进行 nn 次),发现 MM 取 n\sqrt{n} 期望复杂度最小为 o(nlog⁡n)o(n\log\sqrt{n})。

C++
#include <bits/stdc++.h>
using namespace std;
const int N = 1e6+5;
int n,block,t;
int a[N],st[N],ed[N],id[N];
priority_queue <pair<int,pair<int,int> >,vector<pair<int,pair<int,int> > >,greater<pair<int,pair<int,int> > > > q;
int main()
{
	cin >> n;
	block = sqrt(n);
	for(int i = 1;i <= block;i++)
	{
		st[i] = ed[i - 1] + 1;
		ed[i] = i * block;
	}
	for(int i = 1;i <= n;i++) cin >> a[i];
	if(ed[block] < n) block++,ed[block] = n,st[block] = ed[block - 1] + 1;
	for(int i = 1;i <= block;i++) for(int j = st[i];j <= ed[i];j++) id[j] = i;
	id[n + 1] = 0x3f3f3f3f;
	for(int i = 1;i <= block;i++)
	{
		sort(a + st[i],a + ed[i] + 1);
		q.push({a[st[i]],{st[i],i}});
	}
	for(int i = 1;i <= n;i++)
	{
		pair <int,pair<int,int> > sx = q.top();
		int x = sx.first;
		int y = sx.second.first;
		int z = sx.second.second;
		cout << x << ' ';
		q.pop();
		y++;
		if(id[y] > z) continue ;
		q.push({a[y],{y,z}});
	}
}

2.最小生成树优化最短路

注意到任意点的最短路一定不会形成一个环,所以那么最后我们实际走过的路径为一棵树,考虑最小生成树,复杂度为 n+nlog⁡nn+n\log{n}。

原文