2627 村村通

2627 村村通

 

时间限制: 1 s
空间限制: 32000 KB
题目等级 : 黄金 Gold
 
 
 
 
题目描述 Description

农民约翰被选为他们镇的镇长!他其中一个竞选承诺就是在镇上建立起互联网,并连接到所有的农场。当然,他需要你的帮助。

约翰已经给他的农场安排了一条高速的网络线路,他想把这条线路共享给其他农场。为了用最小的消费,他想铺设最短的光纤去连接所有的农场。

你将得到一份各农场之间连接费用的列表,你必须找出能连接所有农场并所用光纤最短的方案。每两个农场间的距离不会超过100000

输入描述 Input Description

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

输出描述 Output Description

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

样例输入 Sample Input

4
0 4 9 21
4 0 8 17
9 8 0 16
21 17 16 0

样例输出 Sample Output

28

数据范围及提示 Data Size & Hint

暂时无范围。

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<algorithm>
 4 using namespace std;
 5 struct k{
 6     int x,y,v;
 7     
 8 }a[10000];
 9 int fa[1000];
10 int find(int x)
11 {
12     if(fa[x]!=x)
13     {fa[x]=find(fa[x]);
14     return fa[x];
15     }
16     else
17     return x;
18 }
19 void un(int x,int y)
20 {
21     fa[x]=y;
22 }
23 int cmp( k a, k b)      
24 {
25      if (a.v < b.v) return 1;
26         else return 0; 
27 }
28 int main()
29 {
30     int s,m=0;
31     int n;
32     cin>>n;
33     for(int i=1;i<=n;i++)
34      {
35          for(int j=1;j<=n;j++)
36           {
37               cin>>s;
38               if(s!=0)
39                {
40                    m++;
41                    a[m].x=i;
42                    a[m].y=j;
43                    a[m].v=s;
44                }
45           }
46      }
47      for(int i=1;i<=n;i++)
48       {
49           fa[i]=i;
50       }
51       sort(a+1,a+m+1,cmp);
52       int k=0,tot=0;
53      for(int i=1;i<=m;i++)
54       {
55           int r=find(a[i].x);
56           int rr=find(a[i].y);
57           if(r!=rr)
58            {
59                un(r,rr);
60                tot+=a[i].v;
61                k++;
62            }
63         if(k==n-1)
64          {
65              break;
66          }
67       }
68       cout<<tot;
69     return 0;
70 }

 

posted @ 2017-04-13 21:20  ioioioioioio  阅读(113)  评论(0编辑  收藏  举报