P1546

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

题意描述

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

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

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

输入

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

输出

28

点拨

最小生成树板子

代码

#include <iostream>
#include <utility>
#include <algorithm>
using namespace std;
typedef long long ll;
#define fi(i, a, b) for (int i = a; i <= b; ++i)
#define fr(i, a, b) for (int i = a; i >= b; --i)
#define x first
#define y second
#define sz(x) ((int)(x).size())
#define pb push_back
using pii = pair<int, int>;
//#define DEBUG
int n;
int dis[105][105];
int f[105];
struct edge
{
    int a, b, c;
    bool operator < (const edge p) const {
        return c < p.c;
    }
} edge[10005];
int find(int x)
{
    return f[x] == x ? x : f[x] = find(f[x]);
}
void combin(int x, int y)
{
    f[find(x)] = f[find(y)];
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
#ifdef DEBUG
    // freopen(D:\in.txt,r,stdin);
#endif
    cin >> n;
    int p = 0;
    fi(i,1,n) f[i] = i;
    fi(i, 1, n) fi(j, 1, n)
    {
        cin >> dis[i][j];
    }
    fi(i,2,n) fi(j,1,i-1){
        edge[p].a = i;
        edge[p].b = j;
        edge[p++].c = dis[i][j];
    }
    sort(edge,edge+p);
    int ans = 0;
    fi(i,0,p-1){
        int a = edge[i].a;
        int b = edge[i].b;
        int c = edge[i].c;
        a = find(a);
        b = find(b);
        if(a != b){
            combin(a,b);
            ans += c;
        }
    }
    cout << ans << endl;
    return 0;
}
posted @ 2022-03-18 20:44  Sun-Wind  阅读(29)  评论(0编辑  收藏  举报