备忘录 :
prim 算法 堆优化版
#include <bits/stdc++.h>
#define x first
#define y second
#define int long long
const int N = 555, M = 2e5 + 111, INF = 0x3f3f3f3f;
using namespace std;
typedef pair<int, int> P;
int n, m, idx, d[N], h[N], v[N];
struct E{
int v, n, w;
} g[M];
void add (int a, int b, int c) {
g[idx].v = b; g[idx].n = h[a];g[idx].w = c; h[a] = idx ++;
}
int prim () {
memset(d, 0x3f, sizeof d);memset(v, 0, sizeof v);priority_queue<P, vector<P>, greater<P>> que;que.push({
0, 1});d[1] = 0;int cnt = n, res = 0;while (que.size() && cnt) {
auto [x, y] = que.top();que.pop();if (v[y]) continue;v[y] = 1;res += x;cnt --;for (int i = h[y]; i; i = g[i].n) {
int j = g[i].v;if (!v[j] && d[j] > g[i].w) {
d[j] = g[i].w;que.push({
d[j], j});}}}return cnt ? INF : res;
}
signed main() {
cin >> n >> m;idx = 1;for (int i = 1; i <= m; ++ i) {
int a, b, c;cin >> a >> b >> c;add (a, b, c);add (b, a, c);}int t = prim();if (t != INF) cout << t << endl;else cout << "impossible" << endl;return 0;
}
kruskal 算法
#include <bits/stdc++.h>
const int N = 1e5 + 111, M = 1e6 + 111;
using namespace std;
int n, m, p[N];
struct E {
int a, b, l;
}g[M];
int find (int x) {
if (p[x] != x) p[x] = find(p[x]);return p[x];
}
int main() {
cin >> n >> m;for (int i = 1; i <= n; ++ i)p[i] = i;for (int i = 1; i <= m; ++ i) cin >> g[i].a >> g[i].b >> g[i].l;sort(g + 1, g + 1 + m, [](auto& a, auto& b) {
return a.l < b.l;});int cnt = 0, res = 0;for (int i = 1; i <= m; ++ i) {
auto [a, b, l] = g[i]; a = find(a), b = find(b);if (a != b) {
p[a] = b;cnt ++;res += l;if (cnt == n - 1) break;}}if (cnt < n - 1) cout << "impossible" << endl;else cout << res << endl;return 0;
}