COGS【831】最短网络

831. [USACO 3.1] 最短网络

★   输入文件:agrinet.in   输出文件:agrinet.out   简单对比
时间限制:1 s   内存限制:128 MB


usaco/agrinet描述


     农民约翰被选为他们镇的镇长!他其中一个竞选承诺就是在镇上建立起互联网,并连接到所有的场。当然,他需要你的帮助。
     约翰已经给他的农场安排了一条高速的网络线路,他想把这条线路共享给其他农场。为了用最小的消费,他想铺设最短的光纤去连接所有的农场。
     你将得到一份各农场之间连接费用的列表,你必须找出能连接所有农场并所用光纤最短的方案。
每两个农场间的距离不会超过100000
 
 
格式

PROGRAM NAME: agrinet

INPUT FORMAT:(file agrinet.in)

第一行: 农场的个数,N(3<=N<=100)。
第二行..结尾: 后来的行包含了一个N*N的矩阵,表示每个农场之间的距离。理论上,他们是N行,每行由N个用空格分隔的数组成,实际上,他们限制在80个字符,因此,某些行会紧接着另一些行。当然,对角线将会是0,因为不会有线路从第i个农场到它本身。
 

OUTPUT FORMAT:(file agrinet.out)

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

SAMPLE INPUT
(file agrinet.in)
4
0 4 9 21
4 0 8 17
9 8 0 16
21 17 16 0
SAMPLE OUTPUT
(file agrinet.out)

28

kruskal算法,使用并查集,查找连通块。

 1 #include<cstdio>
 2 #include<cstdlib>
 3 #include<cmath>
 4 #include<cstring>
 5 #include<iostream>
 6 #include<vector>
 7 #include<map>
 8 #include<set>
 9 #include<stack>
10 #include<string>
11 #include<algorithm>
12 #define maxn 10000+50
13 #define inf 0x7fffffff
14 #define  xiao 1e-9
15 using namespace std;
16 struct Edge{ int x,y,v;}a[maxn];
17 int fa[maxn];
18 int find(int x) 
19    {
20          if(fa[x]!=x) fa[x]=find(fa[x]);
21          return fa[x];
22    }
23 void unionn(int x,int y)
24 {
25     int faa=find(x);
26     int fab=find(y);
27     if(faa!=fab) fa[faa]=fab;
28 }
29 int cmp(const Edge&m,const Edge&n)
30 {
31     if(m.v<n.v) return 1;
32     else return 0;
33 }
34 int main()
35 {
36     freopen("agrinet.in","r",stdin);
37     freopen("agrinet.out","w",stdout);
38     int n,x,tot=0,ans=0,sum=0;
39     cin>>n;
40     for(int i=1;i<=n;++i) 
41       for(int j=1;j<=n;++j) 
42       {
43           scanf("%d",&x);
44           if(x!=0) 
45             {
46                   tot++;
47                   a[tot].x=i;a[tot].y=j;a[tot].v=x;
48             }
49       }
50     for(int i=1;i<=n;++i) fa[i]=i;
51     sort(a+1,a+tot+1,cmp);
52     for(int i=1;i<=tot;++i)
53     {
54         if(find(a[i].x)!=find(a[i].y)) 
55         {
56             unionn(a[i].x,a[i].y);
57             sum++;
58             ans+=a[i].v;
59         }
60         if(sum==n-1) break;
61     }
62     cout<<ans;
63     fclose(stdin);fclose(stdout);
64 }
65     
原文地址:https://www.cnblogs.com/TYH-TYH/p/4936104.html