HDU-1863 畅通工程
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1863
大意:这个题就是一个最小生成树的问题,这里通过构建一个结构体数组来存储道路的起点和终点,以及这条路的费用。在操作中,实质上还是涉及了并查集的知识,在判断出两个村庄的祖先是不是同一个地方是时候进行merge函数操作,但合并的村庄数目达到了总数目时输出最后的结果即可。但是这里要注意的是,因为是最小生成树,所以在操作之前,我们不得不进行一次sort排序,把所有道路按照价格从小到大排序,然后再进行遍历操作
先定义sort优先级
bool cmp(const node a,const node b){
return a.w<b.w;
}
代码:
#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<cstring>
using namespace std;
struct node{
int u,v,w;
};
node e[100000];
int f[100000];
bool cmp(const node a,const node b){
return a.w<b.w;
}
void init(int x){
for(int i=1;i<=x;i++)
f[i]=i;
}
int find(int x){
if(x==f[x])
return x;
else{
f[x]=find(f[x]);
return f[x];
}
}
int merge(int x,int y){
int t1=find(x);
int t2=find(y);
if(t1!=t2){
f[t2]=t1;
return 0;
}
else
return 1;
}
int main(){
int n,m;
while(scanf("%d %d",&n,&m)!=EOF&&n){
for(int i=1;i<=n;i++)
cin>>e[i].u>>e[i].v>>e[i].w;
init(m);
sort(e+1,e+1+n,cmp);//排序,按照道路的价格从小到大排序
int num=1;
long long sum=0;
for(int i=1;i<=n;i++){
if(merge(e[i].u,e[i].v)==0){
num++;
sum+=e[i].w;
}
if(num==m){
cout<<sum<<endl;
break;
}
}
if(num<m)
cout<<"?"<<endl;
}
return 0;
}