#include <iostream>
#include <string>
#include <map>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <regex>
#include <cctype>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int p[101];
void init(int n){
int i;
for(i=1;i<=n;i++){
p[i]=i;
}
}
int find(int x){
if(x==p[x]) return x;
else return p[x]=find(p[x]);
}
void uni(int x,int y,int& total,int weight){
x=find(x);
y=find(y);
if(x==y) return;
else{
p[y]=x;
total=total+weight;//相比连通图的那个题目,这里要传权重进去,每加入一条边的时候要加上权值
}
}
struct edge{
int a;
int b;
int w;
};
bool comp(edge lhs,edge rhs){
if(lhs.w<rhs.w) return true;
// else if(lhs.w==rhs.w) return true;
//永远不要使用 <= 或 >= 定义比较函数:这会导致违反严格弱序规则,是典型错误。
//如果要实现相等的时候的排序,用stable_sort
else return false;
}
int main() {
int i,j;
vector<edge> g;
int n;
while(cin>>n){
if(n==0) break;
init(n);
for(i=0;i<n*(n-1)/2;i++){
edge e;
cin>>e.a>>e.b>>e.w;
g.push_back(e);
}//构建一个图,用结构体存储的
sort(g.begin(),g.end(),comp);//按照权重排序
int total=0;
for(i=0;i<n*(n-1)/2;i++){
uni(g[i].a,g[i].b,total,g[i].w);//依次将各条边加入并查集
}
cout<<total<<endl;
}
}
// 64 位输出请用 printf("%lld")
用并查集实现克鲁斯卡尔算法求最小生成树
最新推荐文章于 2025-06-13 12:30:35 发布