还是畅通工程 HDU - 1233 (Kruskal)
某省调查乡村交通状况,得到的统计表中列出了任意两村庄间的距离。省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可),并要求铺设的公路总长度为最小。请计算最小的公路总长度。
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.
Hint
Hint
题意:给n组数据 , 分别表示a点到b点的距离为c,输出最短距离(各点之间相连为树状)
思路:把所有边排序一下,从最小的开始找,如果这俩个点的父节点不同,则将他们相连并且将该俩点之间的距离ans+=c;
相同的话,继续下一条边。
最后输出ans即可。
代码:
#include <stdio.h>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;
const int maxn = 100000 + 8;
int father[maxn] ,total;
struct node
{
int a ;
int b ;
int cost;
}s[maxn];
void init()
{
for(int i = 0 ; i < maxn ; i++)
{
father[i] = i;
}
}
int getf(int x)
{
return x == father[x] ? x : father[x] = getf(father[x]);
}
bool cmp(node a , node b)
{
return a.cost < b.cost;
}
bool merge(int x , int y)
{
int fx = getf(x);
int fy = getf(y);
if(fx != fy)
{
father[fx] = fy;
return true;
}
else
{
return false;
}
}
int main()
{
int n , m , ans;
while(scanf("%d" , &n) && n)
{
init();
ans = 0;
m = n * ( n-1)/2;
for(int i = 0 ; i < m ; i++)
{
scanf("%d %d %d" , &s[i].a , &s[i].b , &s[i].cost);
}
sort(s , s+m , cmp);
for(int i = 0 ; i < m ; i++)
{
if(merge(s[i].a , s[i].b))
{
ans += s[i].cost ;
}
else
{
continue;
}
merge(s[i].a , s[i].b);
}
printf("%d\n" , ans);
}
return 0;
}