codevs 1078 最小生成树 kruskal

题目描述 Description

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

输入描述 Input Description

第一行: 农场的个数,N(3<=N<=100)。

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

输出描述 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
题意: 最小生成树
题解: kruscal 模板题目
注意wa点
 
 1 #include<iostream>
 2 #include<cstring>
 3 #include<cstdio>
 4 #include<queue>
 5 #include<algorithm>
 6 #include<stack>
 7 using namespace std;
 8 struct node
 9 {
10     int l;
11     int r;
12     int v;
13 }N[11000];
14 int fa[101];
15 int n;
16 int jishu;
17 int exm;
18 bool cmp(struct node aa,struct node bb)
19 {
20     if(aa.v<bb.v)//wa 点!!! 
21      return true;
22      return false;
23 }
24 void init()
25 {
26     for(int i=1;i<n;i++)
27      fa[i]=i;
28 }
29 int find(int root)
30 {
31     if(root!=fa[root])
32       return fa[root]=find(fa[root]);
33     else
34       return fa[root];
35 }
36 void  unio(int a,int b)
37 {
38     int aa=find(a);
39     int bb=find(b);
40     if(aa!=bb)
41         fa[aa]=bb;
42 }
43 void kruscal()
44 {
45     int ans=0;
46     for(int i=0;i<jishu;i++)
47     {
48       int q=find(N[i].l);
49       int w=find(N[i].r);
50       if(q!=w)
51       {
52           n--;
53           unio(q,w);
54           ans+=N[i].v;
55       }
56       if(n==1)
57       break;
58     }
59     cout<<ans<<endl;
60 }
61 int main()
62 {
63     while(scanf("%d",&n)!=EOF)
64     {
65         init();
66         jishu=0;
67         for(int i=1;i<=n;i++)
68          for(int j=1;j<=n;j++)
69          {
70              scanf("%d",&exm);
71              N[jishu].l=i;
72              N[jishu].r=j;
73              N[jishu++].v=exm; 
74          }
75          sort(N,N+jishu,cmp);
76          kruscal();
77     } 
78     return 0;
79     
80 } 
原文地址:https://www.cnblogs.com/hsd-/p/5397384.html