题目背景
农民约翰被选为他们镇的镇长!他其中一个竞选承诺就是在镇上建立起互联网,并连接到所有的农场。当然,他需要你的帮助。
题目描述
约翰已经给他的农场安排了一条高速的网络线路,他想把这条线路共享给其他农场。为了用最小的消费,他想铺设最短的光纤去连接所有的农场。
你将得到一份各农场之间连接费用的列表,你必须找出能连接所有农场并所用光纤最短的方案。每两个农场间的距离不会超过100000
输入格式
第一行: 农场的个数,N(3<=N<=100)。
第二行…结尾: 后来的行包含了一个N*N的矩阵,表示每个农场之间的距离。理论上,他们是N行,每行由N个用空格分隔的数组成,实际上,他们限制在80个字符,因此,某些行会紧接着另一些行。当然,对角线将会是0,因为不会有线路从第i个农场到它本身。
输出格式
只有一个输出,其中包含连接到每个农场的光纤的最小长度。
输入输出样例
输入
4
0 4 9 21
4 0 8 17
9 8 0 16
21 17 16 0
输出
根据题意我们可以知道,题目要求求出一个边集使所有点联通且边权最小。
由此我们可以想到最小生成树。
于是我们可以依照题意连边,跑一遍最小生成树就可以了。
#include<bits/stdc++.h>
#define ll long long
#define MAXN 500010
#define N 201
#define INF 0x3f3f3f3f
#define gtc() getchar()
using namespace std;
template <class T>
inline void read(T &s){
s = 0; T w = 1, ch = gtc();
while(!isdigit(ch)){if(ch == '-') w = -1; ch = gtc();}
while(isdigit(ch)){s = s * 10 + ch - '0'; ch = gtc();}
s *= w;
}
template <class T>
inline void write(T x){
if(x < 0) putchar('-'), x = -x;
if(x > 9) write(x/10);
putchar(x % 10 + '0');
}
struct node{
int x, y, z;
}e[MAXN];
int n;
int m = 0;
int fa[MAXN];
inline int get(int x){
return x == fa[x] ? x : fa[x] = get(fa[x]);
}
int v[MAXN];
bool cmp(node a, node b){
return a.z < b.z;
}
int main()
{
read(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){
int z; read(z);
e[++m].x = i, e[m].y = j, e[m].z = z;
}
sort(e + 1, e + m + 1, cmp);
int ans = 0;
for(int i = 1; i <= m; ++i){
int x = get(e[i].x), y = get(e[i].y);
if(x != y){
fa[x] = y; ans += e[i].z;
}
}
cout << ans << endl;
return 0;
}