文章
166
粉丝
68
获赞
855
访问
61.6k
#include <bits/stdc++.h>
using namespace std;
struct edge {
int a, b, w;
edge(int a, int b, int w) : a(a), b(b), w(w) {}
bool operator<(edge y) {
return w < y.w;
}
};
vector<int> f;
int findroot(int x) {
return f[x] == x ? x : f[x] = findroot(f[x]);
}
int main() {
int n, m;
while (cin >> n >> m) {
vector<edge> road;
f.resize(n + 1); // 初始化并查集
for (int i = 1; i <= n; i++) f[i] = i;
int component_count = n; // 连通分量计数
while (m--) {
int a, b, w;
cin >> a >> b >> w;
road.push_back(edge(a, b, w));
}
sort(road.begin(), road.end());
int ans = 0;
for (auto x : road) {
int fa = findroot(x.a);
int fb = findroot(x.b);
if (fa != fb) {
component_count--;
f[fa] = fb;
ans +=...
登录后发布评论
暂无评论,来抢沙发