点击查看源代码
还是畅通工程
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 54426 Accepted Submission(s): 24713
Problem Description
某省调查乡村交通状况,得到的统计表中列出了任意两村庄间的距离。省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可),并要求铺设的公路总长度为最小。请计算最小的公路总长度。
Input
测试输入包含若干测试用例。每个测试用例的第1行给出村庄数目N ( < 100 );随后的N(N-1)/2行对应村庄间的距离,每行给出一对正整数,分别是两个村庄的编号,以及此两村庄间的距离。为简单起见,村庄从1到N编号。
当N为0时,输入结束,该用例不被处理。
当N为0时,输入结束,该用例不被处理。
Output
对每个测试用例,在1行里输出最小的公路总长度。
Sample Input
31 2 11 3 22 3 441 2 11 3 41 4 12 3 32 4 23 4 50
Sample Output
35
Huge input, scanf is recommended.
Hint
Hint
这个里面用到了vector的知识点,第一次用,出了不少错误,还好最后还是学会了。
#include <iostream> using namespace std; #include <vector> //vector的头文件 #include <algorithm> int f[105]; struct Road { int x,y; int cost; }; int find(int x) { if(x == f[x]) return f[x]; else { while(x != f[x]) x=f[x]; return f[x]; } } bool cmp(Road a,Road b) { return a.cost<b.cost; } bool join(int x,int y) //定义为bool类型可以检验是否进行了合并 { int fx=find(x); int fy=find(y); if(fx != fy) { f[fx]=fy; return true; } return false; } int main() { int i,m,n,sum,cnt; vector<Road> d; //vector定义变量,<>中为定义的变量类型 Road r; while(cin>>n && n) { m=n*(n-1)/2; for(i=1;i<=n;i++) f[i]=i; d.clear(); //对容器的初始化,即全部清空 ,要用 变量名 .函数 的格式 while(m--) { cin>>r.x>>r.y>>r.cost; d.push_back(r); //在函数尾部添加数据 } sum=cnt=0; sort(d.begin(),d.end(),cmp); //对cost进行排序,begin和end分别为首地址和尾地址+1 for(i=0;i<d.size();i++) //遍历所有的数据,vector的变量相当于一个一个数组,从i=0开始使用 { if(join(d[i].x,d[i].y) == true) //size为其大小 { sum+=d[i].cost; cnt++; } if(cnt == n-1) break; } cout<<sum<<endl; } }