复习最小生成树Kruscal算法。和prime算法相比,Kruscal算法更适合顶点多、边少的稀疏图。prime相对适合顶点偏少的情况
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int father[100005]; // father[i]代表 i 节点的父节点
struct edge { // 边的定义
int x, y, w;
edge() {}
edge(int x, int y, int w) : x(x), y(y), w(w) {}
bool operator < (const edge& oth) const {
return w <= oth.w;
}
};
int find_root(int x) { // 找到 节点 x 所在树的根节点
while (x != father[x])
x = father[x];
return x;
}
void uni(int x, int y) { // 将 x节点所在树与 y 节点所在树合并
int root_x = find_root(x);
int root_y = find_root(y);
father[root_x] = root_y;
}
int main() {
int N, M;
while (cin >> N >> M) {
int x, y, w;
vector<edge> a;
for (int i = 0; i < M; ++i) { // 读入M条边
cin >> x >> y >> w;
a.push_back(edge(x, y, w));
}
for (int i = 1; i <= N; ++i) //初始化每一个节点是一颗树
father[i] = i;
sort(a.begin(), a.end()); // 按照边的权值 从小到大排序
int ans = 0;
for (edge e : a) { // 当边的两个节点 在不同的树中时,合并
if (find_root(e.x) == find_root(e.y)) continue;
ans += e.w;
uni(e.x, e.y);
}
cout << ans << endl;
}
return 0;
}