HDU1233--还是畅通工程--最小生成树--并查集

来源:互联网 发布:二次元软件下载 编辑:程序博客网 时间:2024/04/30 02:37

 

Description

某省调查乡村交通状况,得到的统计表中列出了任意两村庄间的距离。省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可),并要求铺设的公路总长度为最小。请计算最小的公路总长度。
 

Input

测试输入包含若干测试用例。每个测试用例的第1行给出村庄数目N ( < 100 );随后的N(N-1)/2行对应村庄间的距离,每行给出一对正整数,分别是两个村庄的编号,以及此两村庄间的距离。为简单起见,村庄从1到N编号。
当N为0时,输入结束,该用例不被处理。
 

Output

对每个测试用例,在1行里输出最小的公路总长度。
 

Sample Input

31 2 11 3 22 3 441 2 11 3 41 4 12 3 32 4 23 4 50
 

Sample Output

35

Hint

Hint Huge input, scanf is recommended.
 
PS:要求距离最短,显然我们建成的图不能有环,不然的话将环剪掉一条边还是畅通的,具体用并查集实现,先按边的长度排序,如果有一条边(还没建成公路)的两个点分别在两个连通分量中,那就把这条边建成公路
#include <iostream>#include <cstdio>#include <algorithm>using namespace std;#define maxn 108int father[maxn];struct Edge{int u,v,len;}edge[maxn*(maxn-1)];bool cmp(Edge a,Edge b){return a.len>=b.len?0:1;}int find(int x){if(x==father[x]){return x;}return find(father[x]);}int main(){int n;while(cin>>n&&n){int minlen=0;int k=n*(n-1)/2;for(int i=1;i<=n;i++){father[i]=i;}for(int i=1;i<=k;i++){cin>>edge[i].u>>edge[i].v>>edge[i].len;}sort(edge+1,edge+k+1,cmp);for(int i=1;i<=k;i++){if(find(edge[i].u)!=find(edge[i].v)){minlen+=edge[i].len;father[find(edge[i].v)]=edge[i].u;}}cout<<minlen<<endl;}return 0;}

原创粉丝点击