I - Agri-Net
题目链接:https://vjudge.net/contest/66965#problem/I
题目:
农夫约翰当选为他镇上的市长!他的竞选承诺之一是为该地区的所有农场提供互联网连接。当然,他需要你的帮助。
农夫约翰为他的农场订购了一个高速连接,并将与其他农民分享他的连接。为了最大限度地降低成本,他希望将最少量的光纤用于将农场连接到所有其他农场。
给出连接每对农场需要多少光纤的列表,您必须找到将它们连接在一起所需的最少光纤数量。每个服务器场必须连接到其他服务器场,以便数据包可以从任何一个服务器场流向任何其他服务器场。
任何两个农场之间的距离不会超过100,000。
输入
输入包括几种情况。对于每种情况,第一行包含农场数N(3 <= N <= 100)。以下行包含N x N锥度矩阵,其中每个元素显示从场到另一个的距离。从逻辑上讲,它们是N行N个空格分隔的整数。从物理上讲,它们的长度限制为80个字符,因此有些行会继续使用其他行。当然,对角线将为0,因为从农场i到自身的距离对于这个问题并不感兴趣。
产量
对于每种情况,输出一个整数长度,它是连接整组农场所需的最小光纤长度之和。
样本输入
4
0 4 9 21
4 0 8 17
9 8 0 16
21 17 16 0
样本输出
28
思路:该矩阵是农场和其他农场之间的距离,为0说明就是自己和自己的距离,求最小生成树即可,注意多组输入,否则wa
//
// Created by hanyu on 2019/8/1.
//
#include <algorithm>
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <set>
#include<math.h>
using namespace std;
typedef long long ll;
const int maxn=2e7+7;
int father[maxn];
struct Node{
int u,v,w;
bool operator<(const Node &other)const{
return this->w<other.w;
}
}node[maxn];
int find(int x)
{
if(x==father[x])
return x;
return father[x]=find(father[x]);
}
int main()
{
int n;
while(~scanf("%d",&n)) {
int x;
int book = 0;
for (int i = 0; i <= n; i++)
father[i] = i;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
scanf("%d", &x);
if (x != 0) {
node[book].u = i;
node[book].v = j;
node[book++].w = x;
}
}
}
sort(node, node + book);
int res = 0;
int num = 0;
for (int i = 0; i < book; i++) {
int uu = find(node[i].u);
int vv = find(node[i].v);
if (uu == vv)
continue;
else {
res += node[i].w;
father[uu] = vv;
num++;
if (num == n - 1)
break;
}
}
printf("%d\n", res);
}
return 0;
}