用并查集实现克鲁斯卡尔算法求最小生成树

#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")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值