A
来源:互联网 发布:mac 10.10 u盘制作 编辑:程序博客网 时间:2024/06/06 00:19
某省调查乡村交通状况,得到的统计表中列出了任意两村庄间的距离。省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可),并要求铺设的公路总长度为最小。请计算最小的公路总长度。
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
Huge input, scanf is recommended.
#include<cstdio>#include<iostream>#include<cstring>#include<cmath>#include<algorithm>using namespace std;int pre[100001];struct node{ int u,v; int value;}p[100001];void init(int n){ for(int i=0;i<n;i++) { pre[i]=i; }}int find(int x){ if(pre[x]==x) return x; return pre[x]=find(pre[x]);}bool cmp (node x,node y){ return x.value<y.value;}void mix(int x,int y){ int fx=find(x); int fy=find(y); if(fx!=fy) { pre[fy]=fx; }}int main(){ int n; while(scanf("%d",&n)!=EOF&&n!=0) { memset(pre,0,sizeof(pre)); int m=n*(n-1)/2; for(int i=0;i<m;i++) { scanf("%d%d%d",&p[i].u,&p[i].v,&p[i].value); } sort(p,p+m,cmp); int num=0,ans=0; init(n); for(int i=0;i<m&&num<n-1;i++) { int fx=find(p[i].u); int fy=find(p[i].v); if(fx!=fy) { pre[fy]=fx; num++; ans+=p[i].value; } } printf("%d\n",ans); } return 0;}
阅读全文
2 0
- a
- a
- a
- a
- a
- a
- a
- a
- a
- a
- a
- a
- a
- A
- A*
- a
- A
- a
- Android Studio系列教程六--Gradle多渠道打包
- Android程序员学WEB前端(8)-CSS(3)-盒子内联块级定位浮动-Sublime
- 插入排序之--折半插入排序
- 浅谈Android嵌入式状态栏的开发
- spring boot
- A
- [ Tomcat ] Eclispe下 Tomcat内存溢出解决方法
- SVM 支持向量机(2)---不完全线性可分
- IOS上架被拒绝理由和解决方法(持续更新中)
- The authenticity of host '0.0.0.0 (0.0.0.0)' can't be established.
- js 全角/半角转化、平假名/片假名转化、半角片假名转化全角片假名
- Java中的ExceptionInInitializerError异常及解决方法
- 本人菜鸟一枚,今天开始编程,Day1
- js中的typeof和instanceof的用法和区别(附类型判断方法)