码迷,mamicode.com
首页 > 编程语言 > 详细

畅通工程(kruskal算法)

时间:2017-08-07 20:42:25      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:opera   bottom   整数   ==   put   编写程序   input   sample   style   

个人心得:日了狗,WR了俩个小时才发现是少了个vector清理,我也是醉了,不过后面还是对这个有了更好得了解,一是我得算法,而是学长改进

后的算法,改进后得算法还要判断所有村庄是否在连在一起,其实我觉得实必要性不大。

技术分享

省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可)。经过调查评估,得到的统计表中列出了有可能建设公路的若干条道路的成本。现请你编写程序,计算出全省畅通需要的最低成本。

 

 

Input
测试输入包含若干测试用例。每个测试用例的第1行给出评估的道路条数 N、村庄数目M ( < 100 );随后的 N 
行对应村庄间道路的成本,每行给出一对正整数,分别是两个村庄的编号,以及此两村庄间道路的成本(也是正整数)。为简单起见,村庄从1到M编号。当N为0时,全部输入结束,相应的结果不要输出。
 

 

Output
对每个测试用例,在1行里输出全省畅通需要的最低成本。若统计数据不足以保证畅通,则输出“?”。
 

 

Sample Input
3 3 1 2 1 1 3 2 2 3 4 1 3 2 3 2 0 100
 

 

Sample Output
3 ?
 

 

Source
 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<vector>
 5 #include<algorithm>
 6 using namespace std;
 7 const long long maxa=99999999;
 8 int n,m;
 9 struct village
10 {
11     int v;
12     int e;
13     int w;
14     village(int x,int y,int z){
15             v=x,e=y,w=z;
16     }
17     village(){}
18     bool operator <(const village &V)const
19     {
20         return w<V.w;
21 
22     }
23 
24 };
25 vector<village> V;
26 int book[105];
27 void init()
28 {
29     for(int i=1;i<=m;i++)
30         book[i]=i;
31 
32 }
33 int getx(int x)
34 {
35     if(book[x]!=x)
36         book[x]=getx(book[x]);
37     return book[x];
38 }
39 void mergexy(int x,int y)
40 {
41      book[y]=x;
42 }
43 int main()
44 {
45     while(cin>>n>>m)
46     {
47         V.clear();
48         if(n==0) break;
49         init();
50         int t=n;
51         while(t--)
52         {
53             int x,y,z;
54             scanf("%d%d%d",&x,&y,&z);
55             village a(x,y,z);
56             V.push_back(a);
57         }
58         sort(V.begin(),V.end());
59         int number=0;
60         long long sum=0;
61         for(int i=0;i<V.size();i++)
62         {
63             if(getx(V[i].v)!=getx(V[i].e)){
64                 mergexy(getx(V[i].v),getx(V[i].e));
65                 number++;
66                 sum+=V[i].w;
67 
68         }
69         if(number==m-1)  break;
70     }
71     if(number==m-1) cout<<sum<<endl;
72     else cout<<"?"<<endl;
73 
74 
75 }
76 return 0;
77 }

 

畅通工程(kruskal算法)

标签:opera   bottom   整数   ==   put   编写程序   input   sample   style   

原文地址:http://www.cnblogs.com/blvt/p/7300914.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!