最小生成树-模板-Kruskal

2019-08-05


Kruskal:https://blog.csdn.net/luomingjun12315/article/details/47700237


Farmer John has been elected mayor of his town! One of his campaign promises was to bring internet connectivity to all farms in the area. He needs your help, of course.
Farmer John ordered a high speed connection for his farm and is going to share his connectivity with the other farmers. To minimize cost, he wants to lay the minimum amount of optical fiber to connect his farm to all the other farms.
Given a list of how much fiber it takes to connect each pair of farms, you must find the minimum amount of fiber needed to connect them all together. Each farm must connect to some other farm such that a packet can flow from any one farm to any other farm.
The distance between any two farms will not exceed 100,000.
Input
The input includes several cases. For each case, the first line contains the number of farms, N (3 <= N <= 100). The following lines contain the N x N conectivity matrix, where each element shows the distance from on farm to another. Logically, they are N lines of N space-separated integers. Physically, they are limited in length to 80 characters, so some lines continue onto others. Of course, the diagonal will be 0, since the distance from farm i to itself is not interesting for this problem.
Output
For each case, output a single integer length that is the sum of the minimum length of fiber required to connect the entire set of farms.
Sample Input
4
0 4 9 21
4 0 8 17
9 8 0 16
21 17 16 0
Sample Output
28


#include <iostream>
#include <algorithm>
using namespace std;
int tree[105];       //用数组来标记每个结点的父结点
struct len            //用结构体来存储区间长度和村落编号
{
    int lenth;
    int a;
    int b;
}l[5005];
bool cmp(len c, len d)    //自定义比较函数,按距离从小到大排
{
    return c.lenth < d.lenth;
}
int find(int x)       
{
    int a = x, b;
    while(tree[x] != x)    //寻找父结点
        x = tree[x];
    while(a != x)       //标记每个结点的父结点
    {
        b = tree[a];
        tree[a] = x;
        a = b;
    }
    return x;   //返回父结点
}
int main()
{
    int n;
    int a[105][105];
    while(cin >> n && n)
    {
        int m = 0, ans = 0;
        for(int i=0; i<=n; i++)
            tree[i] = i; 
        for(int i=1; i<=n; i++)
            for(int j=1; j<=n; j++)
                cin >> a[i][j];
        for(int i=1; i<=n-1; i++)
            for(int j=i+1; j<=n; j++)
            {
                m++;
                l[m].lenth = a[i][j];
                l[m].a = i;
                l[m].b = j;
            }
        sort(l+1,l+m+1,cmp);
        for(int i=1; i<=m; i++)
        {
            if(find(l[i].a) != find(l[i].b)) 
            {
                ans += l[i].lenth;
                tree[find(l[i].a)]= find(l[i].b);    //令父结点相同
            }
        }
        cout << ans << endl;
    }
    return 0;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容