http://ac.jobdu.com/problem.php?pid=1017
来源:互联网 发布:查士丁尼瘟疫 知乎 编辑:程序博客网 时间:2024/05/01 10:10
- 题目描述:
- 某省调查乡村交通状况,得到的统计表中列出了任意两村庄间的距离。省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可),并要求铺设的公路总长度为最小。请计算最小的公路总长度。
- 输入:
测试输入包含若干测试用例。每个测试用例的第1行给出村庄数目N ( < 100 );随后的N(N-1)/2行对应村庄间的距离,每行给出一对正整数,分别是两个村庄的编号,以及此两村庄间的距离。为简单起见,村庄从1到N编号。
当N为0时,输入结束,该用例不被处理。
- 输出:
对每个测试用例,在1行里输出最小的公路总长度。
- 样例输入:
31 2 11 3 22 3 441 2 11 3 41 4 12 3 32 4 23 4 50
- 样例输出:
35
- #include<iostream>
- #include<cstdio>
- #include<memory.h>
- #include<algorithm>
- #include<cstring>
- #include<cmath>
- #include<cstdlib>
- using namespace std;
- #define MAX 0x7FFFFFFF
- struct Node{
- int dis;
- int a,b;
- bool operator<(const Node & node)const{
- return dis < node.dis;
- }
- };
- Node nodes[11000];
- int father[110];
- int getfather(int i){
- if(father[i] == i)
- return i;
- else{
- father[i] = getfather(father[i]);
- return father[i];
- }
- }
- void merge(int i, int j){
- father[i] = j;
- }
- int main(){
- //freopen("in.txt", "r", stdin);
- int n;
- while(cin>>n, n){
- int times = n*(n-1)/2;
- for(int i=0;i<times;++i){
- scanf("%d%d%d", &nodes[i].a, &nodes[i].b, &nodes[i].dis);
- }
- for(int i=1;i<=n;++i)
- father[i] = i;
- sort(nodes, nodes+times);
- int sum = 0;
- for(int i=0;i<times;++i){
- int fa = getfather(nodes[i].a);
- int fb = getfather(nodes[i].b);
- if(fa!=fb){
- sum += nodes[i].dis;
- merge(fa, fb);//father merge
- }
- }
- printf("%d\n", sum);
- }
- //fclose(stdin);
- return 0;
- }
- http://ac.jobdu.com/problem.php?pid=1017
- http://ac.jobdu.com/problem.php?pid=1008
- http://ac.jobdu.com/problem.php?pid=1009
- http://ac.jobdu.com/problem.php?pid=1007
- http://ac.jobdu.com/problem.php?pid=1033
- http://ac.jobdu.com/problem.php?pid=1005
- http://ac.jobdu.com/problem.php?pid=1006
- http://ac.jobdu.com/problem.php?pid=1003
- http://ac.jobdu.com/problem.php?pid=1035
- http://ac.jobdu.com/problem.php?pid=1032
- http://ac.jobdu.com/problem.php?pid=1030
- http://ac.jobdu.com/problem.php?pid=1029
- http://ac.jobdu.com/problem.php?pid=1028
- http://ac.jobdu.com/problem.php?pid=1027
- http://ac.jobdu.com/problem.php?pid=1026
- http://ac.jobdu.com/problem.php?pid=1025
- http://ac.jobdu.com/problem.php?pid=1024
- http://ac.jobdu.com/problem.php?pid=1023
- Html5学习--------canvas编写简单钟表
- http://ac.jobdu.com/problem.php?pid=1022
- http://ac.jobdu.com/problem.php?pid=1021
- http://ac.jobdu.com/problem.php?pid=1020
- http://ac.jobdu.com/problem.php?pid=1019
- http://ac.jobdu.com/problem.php?pid=1017
- http://ac.jobdu.com/problem.php?pid=1016
- http://ac.jobdu.com/problem.php?pid=1014
- Round #145(Div 2)
- http://ac.jobdu.com/problem.php?pid=1013
- http://ac.jobdu.com/problem.php?pid=1012
- http://ac.jobdu.com/problem.php?pid=1011
- http://ac.jobdu.com/problem.php?pid=1010
- 餐饮经营思考(一)——利润&成本