文章
85
粉丝
0
获赞
531
访问
11.1k
#include <bits/stdc++.h>
using namespace std;
const int Max = 5005;
int fa[Max];
struct Edge {
int u, v, w;
};
vector<Edge> edges;
bool cmp(Edge a, Edge b) {
return a.w < b.w;
}
int find(int x) {
if (fa[x]==x) {
return x;
}
fa[x] = find(fa[x]);
return fa[x];
}
void myUnion(int x, int y) {
int fx = find(x);
int fy = find(y);
fa[fx] = fy;
}
int main() {
int n ,m;
cin >> n >> m;
for (int i = 1;i <= n;i++) {
fa[i] = i;
}
while (m--) {
int u,v,w;
cin >> u >> v >> w;
edges.push_back({u,v,w});
}
sort(edges.begin(), edges.end(), cmp);
int sum = 0;
int count = 0;
for (int i =0;i <edges.size();i++) {
int u = edges[i].u, v = edges[i].v;
if (find(u) != find(v)) {
sum += edges[i].w;
count++;
myUnion(u, v);
}
}
...
登录后发布评论
暂无评论,来抢沙发