kruskal模版 [结构体存图]

kruskal的时间复杂度是O(eloge)。这里因为要给边排序,所以要用结构体存图。 
然后用到了并查集检查两个点是否在同一连通分量里,以为在同一连通分量里的两个点如果链接一定形成了环,就不是树了。

#include <iostream>
#include <vector>
#include <string>
#include <cstring>
#include <algorithm>
#include <cstdio>

using namespace std;

struct EDGE{
    int u;
    int v;
    int w;
};

int n,m;
EDGE edge[1000];
bool vis[2000];
int  father[1000],son[1000];
int sum, edgenum;

int unionnode(int x){ //祖先查询
    return  x == father[x] ? x :  unionnode(father[x]);
}

bool join(int u, int v){
    int root1, root2;
    root1 = unionnode(u);
    root2 = unionnode(v);
    if(root1 == root2){
        return  false;
    }
    else father[root1] = father[root2];
//        if(son[root1] >= son[root2]){  //博客上一个大佬的写法,他在和路径压缩的时候比较了谁的孩子多
//        father[root1] = father[root2];
//        son[root1] += son[root2];
//    }else{
//        father[root2] = father[root1];
//        son[root2] += son[root1];
//    }
    return true;
}

bool cmp(EDGE a,EDGE b){
    if(a.w < b.w)
        return true;
    else
        return false;
}

int main() {
    sum = 0;
    edgenum = 0;
    scanf("%d%d", &n, &m);
    for(int i = 0; i < m; i++){
        int u, v, w;
        scanf("%d%d%d", &u, &v, &w);
        edge[i].u = u;
        edge[i].v = v;
        edge[i].w = w;
    }

    for(int i = 1; i <= n; ++i) //初始化
    {
        father[i] = i;
//        son[i] = 1;
    }

    sort(edge, edge+m,cmp); //排序
    bool flag = false;

    for(int i = 0; i < m; i++){ //核心代码。 依次枚举有序边,如果不在同一个连通分量即不构成环,连接两点
        if(join(edge[i].u, edge[i].v)){
            edgenum++;
            sum += edge[i].w;
            cout << edge[i].u << "--->" << edge[i].v << endl;
        }
        if(edgenum == n - 1 ){ //说明已经成树了
            flag = true;
            break;
        }
    }

    if(flag) {
        cout << sum << endl;

    }else  cout <<"ERROR!\n" << endl;


//    for(int i = 0; i < m; i++){
//        cout << edge[i].w <<endl;
//    }

    return 0;
}
/*
input:
 6 9
 2 4 11
 3 5 13
 4 6 3
 5 6 4
 2 3 6
 4 5 7
 1 2 1
 3 4 9
 1 3 2
output:
1--->2
1--->3
4--->6
5--->6
3--->4
19
 */
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值