kruscal最小生成树

#include <iostream>
#include <stdio.h>
#include <bits/stdc++.h>
using namespace std;

struct edge{
    int from,to,cost;
};
int v,e;
edge E[100];
int fa[100];

bool cmp(edge a,edge b){
    return a.cost<b.cost;
}

void init(){
    for(int i=0;i<v;i++) fa[i]=i;
}
int find(int a){
    if(fa[a]==a) return a;
    else return fa[a]=find(fa[a]);
}

void unit(int a,int b){
    a=find(a);
    b=find(b);
    if(a==b) return;
    fa[a]=b;
}

bool same(int a,int b){
    return find(a)==find(b);
}

int kruskal(){
    int len=0;
    init();
    sort(E,E+e,cmp);
    for(int i=0;i<e;i++){
        edge ee=E[i];
        if(!same(ee.from,ee.to)){
            unit(ee.from,ee.to);
            len+=ee.cost;
        }
    }
    return len;
}
int main(){
    cin>>v>>e;
    for(int i=0;i<e;i++){
        int s,t,c;
        cin>>s>>t>>c;
        E[i].from=s;
        E[i].to=t;
        E[i].cost=c;
    }
    cout<<kruskal();
    return 0;
}
/*
7 10
0 1 2
0 2 5
1 2 4
1 3 6
2 3 2
1 4 10
3 5 1
4 5 3
4 6 5
5 6 9
*/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值