MST的线性算法

· · 个人记录

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

```cpp #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的评测用时](https://www.luogu.com.cn/record/201954788) [kruskal的评测用时](https://www.luogu.com.cn/record/201954633) [线性算法的评测用时](https://www.luogu.com.cn/record/202568581)