第二次授课

[USACO3.1]最短网络 Agri-Net

题目背景

Farmer John 被选为他们镇的镇长!他其中一个竞选承诺就是在镇上建立起互联网,并连接到所有的农场。当然,他需要你的帮助。

题目描述

FJ 已经给他的农场安排了一条高速的网络线路,他想把这条线路共享给其他农场。为了用最小的消费,他想铺设最短的光纤去连接所有的农场。

你将得到一份各农场之间连接费用的列表,你必须找出能连接所有农场并所用光纤最短的方案。每两个农场间的距离不会超过 \(10^5\)

输入格式

第一行农场的个数 \(N\)\(3 \leq N \leq 100\))。

接下来是一个 \(N \times N\) 的矩阵,表示每个农场之间的距离。理论上,他们是 \(N\) 行,每行由 \(N\) 个用空格分隔的数组成,实际上,由于每行 \(80\) 个字符的限制,因此,某些行会紧接着另一些行。当然,对角线将会是 \(0\),因为不会有线路从第 \(i\) 个农场到它本身。

输出格式

只有一个输出,其中包含连接到每个农场的光纤的最小长度。

样例 #1

样例输入 #1

4
0 4 9 21
4 0 8 17
9 8 0 16
21 17 16 0

样例输出 #1

28

代码:

#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
struct node
{
    int u, v, w;
} a[N];
int fa[N];
int Find(int x)
{
    if (fa[x] != x)
        fa[x] = Find(fa[x]);
    return fa[x];
}

signed main()
{
    int n, x, cnt = 0;
    cin >> n;
    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++)
        {
            fa[i] = i;
            cin >> x;
            if (i > j)
                a[cnt++] = {i, j, x};
        }
    sort(a, a + cnt, [&](node a, node b)
         { return a.w < b.w; });

    int ans = 0;
    for (int i = 0; i < cnt; i++)
    {
        int uu = Find(a[i].u), vv = Find(a[i].v);
        if (uu != vv)
            fa[uu] = vv, ans += a[i].w;
    }
    cout << ans << endl;
}
posted @ 2022-10-26 10:35  zzh1206  阅读(22)  评论(0)    收藏  举报