题目描述
某省调查乡村交通状况,得到的统计表中列出了任意两村庄间的距离。省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可),并要求铺设的公路总长度为最小。请计算最小的公路总长度。
输入
测试输入包含若干测试用例。每个测试用例的第1行给出村庄数目N ( < 100 );随后的N(N-1)/2行对应村庄间的距离,每行给出一对正整数,分别是两个村庄的编号,以及此两村庄间的距离。为简单起见,村庄从1到N编号。
当N为0时,输入结束,该用例不被处理。
输出
对每个测试用例,在1行里输出最小的公路总长度。
样例输入 Copy
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
样例输出 Copy
3 5
/*
伪代码:
bool 判断是否将会生成环:
读取将要生成通路的两个坐标
检测老大a,老大b
如果老大a=老大b,则将会形成环
并查集的合并函数
并查集的查找函数
读取城市数量
while(城市数量--)
读取每一个城市的起点,终点,距离,存入结构体数组
对结构体数组进行排序
for(遍历结构体数组)
if(将会生成环)
continue
else
将当前的结构数组记录进入并查集,并统计道路总和。
*/
#include<iostream>
#include<algorithm>
using namespace std;
struct city {
int start;
int end;
int distance;
}c[10000];
int set[10000] = { 0 };
bool cmp(city c1, city c2) {
return c1.distance < c2.distance;
}
int where_are_you_from(int pos) {
while (set[pos] != pos) {
pos = set[pos];
}
return pos;
}
void merge(int start, int end) {
int a = where_are_you_from(start);
int b = where_are_you_from(end);
if (a > b) {
set[a] = b;
}
else if (b > a) {
set[b] = a;
}
}
bool no_loop(int start, int end) {
int a = where_are_you_from(start);
int b = where_are_you_from(end);
if (a == b) {
return 0;
}
return 1;
}
int main()
{
int city_numbers;
while (cin >> city_numbers) {
if (city_numbers == 0)
break;
if (city_numbers == 2)
for (int i = 1; i <= city_numbers; i++) {
set[i] = i;
}
city_numbers = ((city_numbers - 1) * city_numbers) / 2;
if(city_numbers>=3)
for (int i = 1; i <= city_numbers; i++) {
set[i] = i;
}
for (int i = 0; i < city_numbers; i++) {
cin >> c[i].start >> c[i].end >> c[i].distance;
}
sort(c, c + city_numbers, cmp);
int result = 0;
for (int i = 0; i < city_numbers; i++) {
int start = c[i].start;
int end = c[i].end;
if (no_loop(start,end)) {
merge(start, end);
result += c[i].distance;
}
}
cout << result << endl;
}
}