最短网络Agri-Net

【问题描述】
  农民约翰被选为他们镇的镇长!他其中一个竞选承诺就是在镇上建立起互联网,并连接到所有的农场。当然,他需要你的帮助。约翰已经给他的农场安排了一条高速的网络线路,他想把这条线路共享给其他农场。为了用最小的消费,他想铺设最短的光纤去连接所有的农场。你将得到一份各农场之间连接费用的列表,你必须找出能连接所有农场并所用光纤最短的方案。每两个农场间的距离不会超过100000。
【输入格式】
 
第一行:
农场的个数,N3<=N<=100)。
第二行..
后来的行包含了一个N*N的矩阵,表示每个农场之间的距离。理论上,他们是N行,每行由N个用空格分隔的数组成,实际上,他们限制在80个字符,因此,某些行会紧接着另一些行。当然,对角线将会是0,因为不会有线路从第i个农场到它本身。

【输出格式】
    只有一个输出,其中包含连接到每个农场的光纤的最小长度。
【输入样例】agrinet.in
    4
    0  4  9  21
    4  0  8  17
    9  8  0  16
    21 17 16  0
【输出样例】agrinet.out
  28
 1 #include<cstdio>
 2 #include<algorithm>
 3 #include<iostream>
 4 using namespace std;
 5 struct node{
 6     int x;
 7     int y;
 8     int v;
 9     bool operator < (const node &aa)const
10     {
11               if(v<aa.v)return 1;
12             else return 0;    
13     }
14 }a[1001];
15 int father[10001];
16 int find(int x)
17 {
18     if(father[x]!=x) father[x]=find(father[x]);
19     return father[x];
20 }
21 void unionn(int x,int y)
22 {
23     /*int fa=find(x);
24     int fb=find(y);
25     if(fa!=fb)father[fa]=fb;*/
26     if(find(x)!=find(y))father[find(x)]=father[find(y)];
27 }
28 int num=0;
29 int main()
30 {
31     int n,m=0,x;
32     scanf("%d",&n);
33     for(int i=1;i<=n;i++)
34     for(int j=1;j<=n;j++)
35     {
36         cin>>x;
37         if(x!=0)
38         {
39             m++;
40             a[++num].x=i;
41             a[num].y=j;
42             a[num].v=x;
43         }
44     }
45     int tot=0,k=0;
46     for(int i=1;i<=n;i++)
47     father[i]=i;
48     sort(a+1,a+m+1);
49     for(int i=1;i<=m;i++)
50     {
51         if(find(a[i].x)!=find(a[i].y))
52         {
53             unionn(a[i].x,a[i].y);
54             tot+=a[i].v;
55             k++;
56         }
57         if(k==n-1)break;
58     }
59     cout<<tot<<endl;
60     return 0;
61 }
原文地址:https://www.cnblogs.com/sssy/p/6705304.html