还是畅通工程

Time Limit:2000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u

Description

某省调查乡村交通状况,得到的统计表中列出了任意两村庄间的距离。省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可),并要求铺设的公路总长度为最小。请计算最小的公路总长度。 
 

Input

测试输入包含若干测试用例。每个测试用例的第1行给出村庄数目N ( < 100 );随后的N(N-1)/2行对应村庄间的距离,每行给出一对正整数,分别是两个村庄的编号,以及此两村庄间的距离。为简单起见,村庄从1到N编号。 
当N为0时,输入结束,该用例不被处理。 
 

Output

对每个测试用例,在1行里输出最小的公路总长度。 
 

Sample Input

3
1 2 1
1 3 2
2 3 4
4
1 2 1
1 3 4
1 4 1
2 3 3
2 4 2
3 4 5
0
 

Sample Output

3 5

Hint

Hint Huge input, scanf is recommended.


//显然,这是一道模板题

//kruskal  1788kb 374ms

 1 #include <stdio.h>
 2  #include <string.h>
 3  #include <algorithm>
 4  using namespace std;
 5  
 6  struct Bian
 7  {
 8      int u,v;
 9      int w;
10  }bian[10005];
11  int p[105];
12  
13  bool cmp(Bian a,Bian b)
14  {
15      return a.w<b.w;
16  }
17  
18  int find (int x)
19  {
20      if (x!=p[x])
21          p[x]=find(p[x]);
22      return p[x];
23  }
24  
25  void kruskal(int n,int m)
26  {
27      int i,num=1,ans=0;
28      int x,y;
29      for (i=1;i<=n;i++) p[i]=i;//初始化并查集
30      sort(bian+1,bian+m+1,cmp);
31      for (i=1;i<=m&&num<=n;i++)
32      {
33          x=find(bian[i].u);
34          y=find(bian[i].v);
35          if(x!=y)         //有点未连通
36          {
37              ans+=bian[i].w;
38              p[x]=y;      //并查集的合并
39              num++;
40          }
41      }
42      printf("%d
",ans);
43  }
44  
45  int main()
46  {
47      int n,m;         //n个点,m条边
48      int i;
49      int a,b,c;
50      while (scanf("%d",&n)&&n)
51      {
52          m=n*(n-1)/2;
53          for(i=1;i<=m;i++)
54          {
55              scanf("%d%d%d",&a,&b,&c);
56              bian[i].u=a;
57              bian[i].v=b;
58              bian[i].w=c;
59          }
60          kruskal(n,m);
61      }
62      return 0;
63  }
View Code

 

 

 

原文地址:https://www.cnblogs.com/haoabcd2010/p/5709767.html