洛谷 P1546:最短网络 ← Kruskal算法模板题

【题目来源】
https://www.luogu.com.cn/problem/P1546
https://www.acwing.com/problem/content/1142/

【题目描述】
农夫约翰被选为他们镇的镇长!
他其中一个竞选承诺就是在镇上建立起互联网,并连接到所有的农场。
约翰已经给他的农场安排了一条高速的网络线路,他想把这条线路共享给其他农场。
约翰的农场的编号是1,其他农场的编号是 2∼n。
为了使花费最少,他希望用于连接所有的农场的光纤总长度尽可能短。
你将得到一份各农场之间连接距离的列表,你必须找出能连接所有农场并使所用光纤最短的方案。

【输入格式】
第一行包含一个整数 n,表示农场个数。
接下来 n 行,每行包含 n 个整数,输入一个对角线上全是0的对称矩阵。
其中第 x+1 行 y 列的整数表示连接农场 x 和农场 y 所需要的光纤长度。

【输出格式】
输出一个整数,表示所需的最小光纤长度。

【数据范围】
3≤n≤100
每两个农场间的距离均是非负整数且不超过100000。

【输入样例】
4
0  4  9  21
4  0  8  17
9  8  0  16
21 17 16  0

【输出样例】
28

【算法分析】
本题采用“
邻接矩阵”存图。也是一道 Kruskal 算法模板题。
另一道 Kruskal 算法模板题详见:
https://blog.csdn.net/hnjzsyjyj/article/details/139606429

【算法代码】

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

const int maxn=105;
int pre[maxn];
int n;

struct edge {
    int u,v;
    int cost;
} e[maxn*maxn]; //keypoint

bool cmp(edge x, edge y) {
    return x.cost<y.cost;
}

int find(int x) { //DSU's find
    if(x!=pre[x]) pre[x]=find(pre[x]);
    return pre[x];
}

void Kruskal() {
    int cnt=0;
    for(int i=1; i<=n; i++) pre[i]=i; //Initialize DSU

    for(int i=1; i<=n; i++) {
        for(int j=1; j<=n; j++) {
            int x;
            cin>>x;
            if(i<j) e[cnt++]= {i,j,x}; //i<j
        }
    }

    sort(e,e+cnt,cmp);

    int ans=0;
    for(int i=0; i<cnt; i++) {
        int fx=find(e[i].u);
        int fy=find(e[i].v);
        if(fx!=fy) {
            pre[fy]=fx;
            ans+=e[i].cost;
        }
    }
    cout<<ans<<endl;
}

int main() {
    cin>>n;
    Kruskal();

    return 0;
}

/*
in:
4
0  4  9  21
4  0  8  17
9  8  0  16
21 17 16  0

out:
28
*/




【参考文献】
https://blog.csdn.net/hnjzsyjyj/article/details/139605698
https://blog.csdn.net/hnjzsyjyj/article/details/139606429



 

  • 12
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值