08-图7 公路村村通 (30分)
现有村落间道路的统计数据表中,列出了有可能建设成标准公路的若干条道路的成本,求使每个村落都有公路连通所需要的最低成本。
输入格式:
输入数据包括城镇数目正整数N(≤1000)和候选道路数目M(≤3N);随后的M行对应M条道路,每行给出3个正整数,分别是该条道路直接连通的两个城镇的编号以及该道路改建的预算成本。为简单起见,城镇从1到N编号。
输出格式:
输出村村通需要的最低成本。如果输入数据不足以保证畅通,则输出−1,表示需要建设更多公路。
输入样例:
6 15
1 2 5
1 3 3
1 4 7
1 5 4
1 6 2
2 3 4
2 4 6
2 5 2
2 6 6
3 4 6
3 5 1
3 6 1
4 5 10
4 6 8
5 6 3
输出样例:
12
最小生成树问题,采用并查集
#include<stdio.h>
#include<algorithm>
using namespace std;
struct node{
int c1;
int c2;
int cost;
};
int tree[1001];
void init(int n){
int i;
for(i=1;i<=n;i++){
tree[i]=-1;
}
}
bool comp(node a,node b){
return a.cost<b.cost;
}
int findroot(int x){
if(tree[x]==-1)return x;
return tree[x]=findroot(tree[x]);
}
int main(){
int n,m,i,j,c1,c2,cost;
scanf("%d %d",&n,&m);
struct node stu[m];
for(i=0;i<m;i++){
scanf("%d %d %d",&stu[i].c1,&stu[i].c2,&stu[i].cost);
}
sort(stu,stu+m,comp);
cost=0;
init(n);
for(i=0;i<m;i++){
int a=findroot(stu[i].c1);
int b=findroot(stu[i].c2);
if(a!=b){
tree[a]=b;
cost=cost+stu[i].cost;
}
}
int cou=0;
for(i=1;i<=n;i++){
if(tree[i]==-1){
cou++;
}
}
if(cou==1){
printf("%d",cost);
}
else{
printf("-1");
}
}