许诺 • 24天前
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Edge {
int x, y, z;
};
bool compare(Edge a, Edge b) {
return a.z < b.z;
}
int parent[101];
int find(int x) {
if (parent[x] != x) {
parent[x] = find(parent[x]);
}
return parent[x];
}
void unite(int x, int y) {
int fx = find(x);
int fy = find(y);
if (fx != fy) {
parent[fy] = fx;
}
}
int main() {
int n, m;
cin >> n >> m;
vector<Edge> edges;
for (int i = 0; i < m; i++) {
int x, y, z;
cin >> x >> y >> z;
edges.push_back({x, y, z});
}
sort(edges.begin(), edges.end(), compare);
for (int i = 1; i <= n; i++) {
parent[i] = i;
}
int sum = 0;
int count = 0;
for (Edge e : edges) {
int fx = find(e.x);
int fy = find(e.y);
if (fx != fy) {
sum += e.z;
unite(e.x, e.y);
count++;
if (count == n - 1) {
break;
}
}
}
cout << sum << endl;
return 0;
}
不想理了,自己复制吧
评论:
请先登录,才能进行评论