文章
1
粉丝
65
获赞
1
访问
7.5k
#include<bits/stdc++.h>
using namespace std;
int father[20000];
struct edge {
int begin;
int end;
int weight;
edge(int a, int b, int c) {
begin = a;
end = b;
weight = c;
}
};
bool cmp(edge &e1, edge &e2) {
return e1.weight < e2.weight;
}
int find(int x) {
if (x == father[x]) return x;
father[x] = find(father[x]);
return father[x];
}
int main() {
vector<edge> Edge;
int n, m;
cin >> n >> m;
for (int i = 0; i<n; i++) father[i] = i;
for (int j = 0; j<m; j++) {
int a, b, c;
cin >> a >> b >> c;
Edge.push_back(edge(a, b, c));
}
sort(Edge.begin(), Edge.end(), cmp);
int k = 0, res = 0;
for (int i = 0; i<m; i++) {
if (k == n - 1) break;
int father_a = find(Edge[i].begin);
int father_b = find(Edge[i].end);
if (father_a != father_b) {
father[father_b] = father_a;
k++;
res += Edge[i].weight;
}
}
if (k == n - 1) cout << res << en...
登录后发布评论
暂无评论,来抢沙发