最小生成树——Kruskal

Kruskal描述:

不断加入不会形成环的当前权值最小边,直到全连通

并查集

int find(int x)
{
    p[x] == x ? x : find(p[x]);//如果p[x]等于x则说明x为当前树根,否则继续寻找他父结点的根结点
}

把x的父结点保存在p[x]中(如果x没有父结点,则p[x]等于x)

间接排序

排序的关键字是对象的“序号”,而不是对象本身

CODE

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <stack>
#include <cctype>//转化大小写
#include <deque>
#include <map>
#include <set>
#include <vector>
#include <string>
#include <queue>
#include <functional>
#include <time.h>
using namespace std;
int u[100],v[100],w[100],r[100];
int p[1000];
int m,n;
int cmp(const int i, const int j)//间接排序
{
    return w[i] < w[j];
}
int find(int x)//并查集
{
    return p[x] == x ? x : p[x] = find(p[x]);
}
int Kruskal()
{
    int ans = 0;
    for(int i=0; i<n; i++) p[i] = i;//初始化并查集
    for(int i=0; i<m; i++) r[i] = i;//初始化序号
    sort(r,r+m,cmp);//给边排序
    for(int i=0; i<m; i++){
        int e = r[i];
        int x = find(u[e]);//找出当前边两个端点所在集合编号
        int y = find(v[e]);
        if(x != y){//如果集合不同则合并
            cout << u[e] << "->" << v[e] << endl;//输出最小生成树边的信息
            ans += w[e];
            p[x] = y;
        }
    }
    return ans;
}
int main()
{
    cin >> n >> m;
    for(int i=0;i<m;i++)
        cin >> u[i] >> v[i] >> w[i];
    cout << Kruskal() << endl;//输出最小生成树总权值
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值