【洛谷 1546】最短网络

题目背景

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

题目描述

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

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

输入格式

第一行农场的个数 NN(3 leq N leq 1003N100)。

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

输出格式

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

输入输出样例

输入 #1
4
0 4 9 21
4 0 8 17
9 8 0 16
21 17 16 0
输出 #1
28

说明/提示

题目翻译来自NOCOW。

USACO Training Section 3.1

题解:水一题最小生成树¥%

#include<cstdio>
#include<iostream>
#include<cmath>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<bits/stdc++.h>
typedef long long ll;
using namespace std;
const int N=200003;
struct node{
    int x,y,w;
}e[N];
int n,m,fa[N],tot,xx,cnt,ans;
void add(int x,int y,int z){
    e[++cnt].x=x;
    e[cnt].y=y;
    e[cnt].w=z;
}
bool cmp(node pp,node qq){
    return pp.w<qq.w; 
}

int find(int x){
    if(x!=fa[x]) 
       x=find(fa[x]);
    return fa[x];
}

int main(){
    freopen("1546.in","r",stdin);
    freopen("1546.out","w",stdout);
    scanf("%d",&n);
    for(int i=1;i<=n;i++) fa[i]=i;
    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++){
            scanf("%d",&xx);
            if(j>i) add(i,j,xx);
        }
    }
    sort(e+1,e+cnt+1,cmp);
    for(int i=1;i<=cnt;i++){
        int uu=find(e[i].x);
        int vv=find(e[i].y);
        if(uu==vv) continue;
        ans+=e[i].w;
        fa[uu]=vv; tot++;
        if(tot==n-1) break; 
    }
    cout<<ans;
    return 0;
}
原文地址:https://www.cnblogs.com/wuhu-JJJ/p/13906530.html