L i n k Link Link
luogu 1546
ssl 1682
ssl 1764(有一点点小区别)
D e s c r i p t i o n Description Description
农民约翰被选为他们镇的镇长!他其中一个竞选承诺就是在镇上建立起互联网,并连接到所有的农场。当然,他需要你的帮助。约翰已经给他的农场安排了一条高速的网络线路,他想把这条线路共享给其他农场。为了用最小的消费,他想铺设最短的光纤去连接所有的农场。你将得到一份各农场之间连接费用的列表,你必须找出能连接所有农场并所用光纤最短的方案。每两个农场间的距离不会超过 100000 100000 100000
I n p u t Input Input
第一行: 农场的个数,N(3<=N<=100)。
第二行…结尾: 后来的行包含了一个N*N的矩阵,表示每个农场之间的距离。理论上,他们是N行,每行由N个用空格分隔的数组成,实际上,他们限制在80个字符,因此,某些行会紧接着另一些行。当然,对角线将会是0,因为不会有线路从第i个农场到它本身
O u t p u t Output Output
只有一个输出,其中包含连接到每个农场的光纤的最小长度。
S a m p l e Sample Sample I n p u t Input Input
4
0 4 9 21
4 0 8 17
9 8 0 16
21 17 16 0
S a m p l e Sample Sample O u t p u t Output Output
28
T r a i n Train Train o f of of T h o u g h t Thought Thought
并查集算法
K
r
u
s
k
a
l
Kruskal
Kruskal思路大概和最优布线问题思路2是差不多一样的,如下
先将图中边的权值排序,然后找到的边若不在一个集合内,就将这个边的两个点收入集合,并加上当前边的权值于最终答案中,当所有点都处于一个集合中时,我们就求出答案了
C o d e Code Code
#include<cmath>
#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
bool b[5001];
int answer,ans,n,t,f[5001];
struct node
{
int fr,to,ti;
}a[25000005];
bool cmp(node xx,node yy)
{
return xx.ti<yy.ti;
}
int find(int x)
{
if (f[x]==x) return x;
else return f[x]=find(f[x]);
}
void merge(int x,int y)
{
int xx=find(x);
int yy=find(y);
if (xx<yy) f[xx]=f[yy];
else f[yy]=f[xx];
}
int main()
{
scanf("%d",&n);
for (int i=1; i<=n; ++i) f[i]=i;
for (int i=1; i<=n; ++i)
for (int j=1; j<=n; ++j)
{
int x;
scanf("%d",&x);
if (x!=0) {a[++t]=(node){i,j,x};}
}
int k=0;
sort(a+1,a+t+1,cmp);
for (int i=1; i<=t; ++i)
{
if (find(a[i].fr)!=find(a[i].to)) {
merge(a[i].fr,a[i].to);
ans+=a[i].ti;
k++;
}
if (k==n-1) break;
}
printf("%d",ans);
}
代码是ssl 1764的