Kruskal算法求最小生成树

Kruskal算法求最小生成树


· 在这里插入代码片



//struct 


1. struct edges

2. 输入边

3. 初始化并查集

4. 给边排序
5. 然后从小到大归并边 要求不连通 使用并查集来判断是否联通

6. 比较 cnt 与 n的大小
#include <iostream>
#include <algorithm>

using namespace std;
const int N=200005;
int n,m; 
int p[N]; //并查集数组

struct edges
{
    int a,b,w;
    bool operator < (const edges &W )const{
        return w<W.w;
    }
}edges[N];
//并查集

int find(int x){
    if(p[x]!=x) p[x] = find(p[x]);
    return p[x];
}
int main(){
    
    int cnt=0;
    int res=0;
    cin>>n>>m;
    int a,b,w; //边
    for(int i=1;i<=n ;i++)///初始化并查集
        p[i] = i;
    for(int i=0;i<m;i++){
        int a,b,w;
        cin>>a>>b>>w;
        edges[i] ={a,b,w};
        
    }
    sort(edges,edges+m);
    for(int i=0;i<m;i++)
    {
        
        cin>>a>>b>>w;
        int a= edges[i].a;
        int b= edges[i].b;
        int w= edges[i].w;
        if(find(a)!= find(b)){
            cnt +=1; // 连接的边数;
            res +=w;
            p[find(a)] = find(b); //连接到并查集中
        }
    }
    if(cnt< n-1 )cout<<"impossible"<<endl;
    else cout<<res<<endl;
    
    
    
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值