跳到正文

个人记录

MST的线性算法

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

文章信息

发布
2025年2月8日
收录
2026年1月29日
更新
2026年11月8日
篇幅
约 3 分钟

版本

  1. v1当前

很简单,当个乐子看就行。

kruskalkruskal的改进版,时间复杂度O(n+m)O(n+m),适用于边权较小((maxi=1mvi−mini=1mvi)≤107(max^m_{i=1}v_i-min^m_{i=1}v_i)≤10^7)的情况。主要用桶排序和链表优化了复杂度。

C++
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 5e5 + 10, M = 1e7 + 10;
int f[N], cnt;
void build(int n)
{
	cnt = n;
	for(int i = 1;i <= n;++i)
		f[i] = i;
}
int find(int x)
{
	return x == f[x] ? x : f[x] = find(f[x]);
}
void merge(int u, int v)
{
	int r1 = find(u), r2 = find(v);
	if(r1 == r2)
		return;
	f[r1] = r2;
	cnt--;
}
int head[M], tail[M], nxt[M], tot;
pair<int, int> h[M];
void insert(int u, int v, int w)
{
	tot++;
	if(!head[w])
		head[w] = tot;
	nxt[tail[w]] = tot;
	tail[w] = tot;
	h[tot] = make_pair(u, v);
}
int read()
{
	int x = 0;
	char ch = getchar();
	while(ch < '0' || ch > '9')
		ch = getchar();
	while('0' <= ch && ch <= '9')
	{
		x = (x << 1) + (x << 3) + ch - '0';
		ch = getchar();
	}
	return x;
}
int n, m, maxn;
ll FsMst()
{
	build(n);
	ll mst = 0;
	for(int i = 1;i <= maxn;++i)
	{
		for(int j = head[i];j;j = nxt[j])
		{
			if(find(h[j].first) == find(h[j].second))
				continue;
			merge(h[j].first, h[j].second);
			mst += i;
		}
	}
	return cnt == 1 ? mst : -1;
}
int main()
{
	n = read(), m = read();
	int u, v, w;
	while(m--)
	{
		u = read(), v = read(), w = read();
		maxn = max(maxn, w);
		insert(u, v, w);
	}
	ll ans = FsMst();
	if(ans == -1)
		cout << "orz";
	else
		cout << ans;
	return 0;
}

对比一下模版题的评测用时 (无O2) :

prim的评测用时

kruskal的评测用时

线性算法的评测用时

原文