08-图7 公路村村通 (30分)

08-图7 公路村村通   (30分)

现有村落间道路的统计数据表中,列出了有可能建设成标准公路的若干条道路的成本,求使每个村落都有公路连通所需要的最低成本。

输入格式:

输入数据包括城镇数目正整数NN\le 10001000)和候选道路数目MM\le 3N3N);随后的MM行对应MM条道路,每行给出3个正整数,分别是该条道路直接连通的两个城镇的编号以及该道路改建的预算成本。为简单起见,城镇从1到NN编号。

输出格式:

输出村村通需要的最低成本。如果输入数据不足以保证畅通,则输出-11,表示需要建设更多公路。

输入样例:

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");
	}
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值