跳到正文

个人记录

最小生成树

Liuyanting1约 2 分钟
原文
文章信息与版本

文章信息

发布
2026年11月22日
收录
2026年11月30日
更新
2026年11月30日
篇幅
约 2 分钟

版本

  1. v1当前
C++
#include <bits/stdc++.h>
using namespace std;
struct P {
    int u, v, w;
};
int n, m, fa[5010];
vector<P> edg;
int cmp (P a1, P a2) {
    return a1.w < a2.w;
}
int find (int x) {
    if (x == fa[x]) return x;
    return fa[x] = find(fa[x]);
}
void kruskal () {
    for (int i = 1; i <= n; i++) fa[i] = i;
    sort(edg.begin(), edg.end(), cmp);
    int cnt = n, res = 0;
    for (auto e : edg) {
        int fx = find(e.u), fy = find(e.v);
        if (fx != fy) {
            fa[fx] = fy;
            cnt--;
            res += e.w;
        }
    }
    if (cnt == 1) cout << res;
    else cout << "orz";
}
int main ()
{
    cin >> n >> m;
    for (int i = 1; i <= m; i++) {
        int x, y, z;
        cin >> x >> y >> z;
        edg.push_back({x, y, z});
    }
    kruskal ();
    return 0;
}
原文