首页 > 编程语言 > 详细

Kruskal算法

时间:2020-07-28 22:03:27      阅读:71      评论:0      收藏:0      [点我收藏+]
#include<iostream>
#include<algorithm>
#define maxn 10005
using namespace std;

int fa[maxn];
void init(){
    for(int i=0;i<maxn;i++){
        fa[i]=i;
    }
}
int get_ancestor(int x){
    if(fa[x]==x){
        return x;
    }
    return fa[x]=get_ancestor(fa[x]);
}
void get_union(int x,int y){
    int fx=get_ancestor(x);
    int fy=get_ancestor(y);
    if(fx!=fy){
        fa[fx]=fy;
    }
}
struct EdgeNode{
    int from,to,weight;
};
EdgeNode edge[maxn];
bool cmp(EdgeNode a,EdgeNode b){
    return a.weight<b.weight;
}
int main(){
    cout<<"请输入顶点数、边数:";
    int n,e;
    cin>>n>>e;
    cout<<"请输入各条边及权重:"<<endl;
    for(int i=0;i<e;i++){
        cin>>edge[i].from>>edge[i].to>>edge[i].weight;
    }
    sort(edge,edge+e,cmp);//按权重从小到大排序
    init();//并查集初始化
    int sum=0,k=0;//sum为代价,k为并入的边数
    for(int i=0;i<e;i++){
        if(k==n-1) break;
        if(get_ancestor(edge[i].from)!=get_ancestor(edge[i].to)){
            get_union(edge[i].from,edge[i].to);
            sum=sum+edge[i].weight;
            k++;
        }
    }
    cout<<"最小代价为:"<<sum<<endl;
    return 0;
}
//请输入顶点数、边数:4 5
//请输入各条边及权重:
//0 1 4
//1 2 5
//2 0 6
//2 3 7
//3 0 8
//最小代价为:16

 

Kruskal算法

原文:https://www.cnblogs.com/zzyf/p/13392517.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!