题目描述
某省调查乡村交通状况,得到的统计表中列出了任意两村庄间的距离。省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可),并要求铺设的公路总长度为最小。请计算最小的公路总长度。
输入描述:
测试输入包含若干测试用例。每个测试用例的第1行给出村庄数目N ( < 100 );随后的N(N-1)/2行对应村庄间的距离,每行给出一对正整数,分别是两个村庄的编号,以及此两村庄间的距离。为简单起见,村庄从1到N编号。
当N为0时,输入结束,该用例不被处理。
输出描述:
对每个测试用例,在1行里输出最小的公路总长度。
示例1
输入
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
输出
3
5
题目解析:要求连通的长度最短,所有应该先按长度进行排序,然后使用并查集找出最短长度。
代码:
#include<stdio.h>
#include<math.h>
#include<algorithm>
#include<string.h>
#include<iostream>
#include<iomanip>
#include<vector>
#include<map>
#include<set>
#include<stack>
#include<queue>
using namespace std;
const int N = 1000;
const int M = 1000000;
int Tree[N];
int findroot(int x){
if(Tree[x] == -1){
return x;
}else{
return findroot(Tree[x]);
}
}
int main()
{
int n , m , begin , end;
while(cin >> n >> m){
memset(Tree , -1 , sizeof(Tree));
for(int i = 0 ; i < m ; i++){
cin >> begin >> end;
int a = findroot(begin);
int b = findroot(end);
if(a != b){
Tree[b] = a;
}
}
int count = -1;
for(int i = 1; i <= n; i++){
int a = findroot(i);
if(a == i){
count++;
}
}
cout << count << endl;
}
return 0;
}
/* 上面是遍历了所有的点,查看是否和其他连通,下面是直接计算边的数量就行了
如果连通的话,肯定是最小生成树,所以 边 = 节点数-1
#include<stdio.h>
#include<math.h>
#include<algorithm>
#include<string.h>
#include<iostream>
#include<fstream>
#include<iomanip>
#include<vector>
#include<regex>
#include<map>
#include<set>
#include<stack>
#include<queue>
using namespace std;
const int N = 1000;
const int M = 500000;
int Tree[N];
int findroot(int x){
if(Tree[x] == -1){
return x;
}else{
return findroot(Tree[x]);
}
}
int main(){
int n , m , begin , end;
while(cin >> n >> m){
int count = 0;
memset(Tree , -1 , sizeof(Tree));
for(int i = 0 ; i < m ; i++){
cin >> begin >> end;
int a = findroot(begin);
int b = findroot(end);
if(a != b){
count++;
Tree[b] = a;
}
}
cout << (n - 1 - count) << endl;
}
return 0;
}
*/
本文详细解析了如何使用最小生成树算法解决乡村公路建设问题,通过并查集算法找到连接所有村庄的最短路径,实现了全省任何两村庄间公路交通的最小总长度。
1776

被折叠的 条评论
为什么被折叠?



