HDU 1863 畅通工程(最小生成树)

畅通工程(最小生成树)

Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 25885    Accepted Submission(s): 11282


Problem Description
省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可)。经过调查评估,得到的统计表中列出了有可能建设公路的若干条道路的成本。现请你编写程序,计算出全省畅通需要的最低成本。
 

Input
测试输入包含若干测试用例。每个测试用例的第1行给出评估的道路条数 N、村庄数目M ( < 100 );随后的 N
行对应村庄间道路的成本,每行给出一对正整数,分别是两个村庄的编号,以及此两村庄间道路的成本(也是正整数)。为简单起见,村庄从1到M编号。当N为0时,全部输入结束,相应的结果不要输出。
 

Output
对每个测试用例,在1行里输出全省畅通需要的最低成本。若统计数据不足以保证畅通,则输出“?”。
 

Sample Input
  
  
3 3 1 2 1 1 3 2 2 3 4 1 3 2 3 2 0 100
 

Sample Output
  
  
3 ?
 

Source
 

Recommend
lcy   |   We have carefully selected several similar problems for you:   1879  1875  1102  1301  1874 


思路:

纯真学姐逗逗的在这里说话,我们就这样的默默在敲代码。

很基础的克鲁斯卡尔算法,判断”数据能否以保证畅通“,利用树的性质:

边数 = 节点数-1. 


代码(克鲁斯卡尔):

0MS 1424K 

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
const int MYDD=1103;

int n,m;
int set[MYDD];//并查集的根节点
void init() {
	for(int j=1; j<=m; j++)
		set[j]=j;
}

int find(int x) {
	int child=x,t;
	while(x!=set[x])
		x=set[x];
	while(x!=child) {
		t=set[child];
		set[child]=x;
		child=t;
	}
	return x;
}

bool combine(int x,int y) {
	int fx=find(x);
	int fy=find(y);
	if(fx!=fy) {
		set[fx]=fy;
		return true;
	}
	return false;
}

struct EDGE { //存储边信息
	int u,v,w;
} edge[MYDD];
bool cmp(EDGE x,EDGE y) {
	return x.w<y.w;
}

int main() {
	while(scanf("%d",&n)&&n!=0) {
		scanf("%d",&m);
		init();
		for(int j=1; j<=n; j++)
			scanf("%d%d%d",&edge[j].u,&edge[j].v,&edge[j].w);

		sort(edge+1,edge+n+1,cmp);

		int count=0;//统计已增加的边数
		int ans=0;
		for(int j=1; j<=n; j++) {
			if(combine(edge[j].u,edge[j].v)) {
				count++;
				ans+=edge[j].w;
			}
		}
//		printf("**********%d\n",count);
		if(count==m-1)
			printf("%d\n",ans);
		else
			puts("?");
	}
	return 0;
}

后:

************************


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值