现在的位置: 首页 > 综合 > 正文

HDU1863 畅通工程 【最小生成树Prim】

2015年12月04日 ⁄ 综合 ⁄ 共 1258字 ⁄ 字号 评论关闭

畅通工程

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

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 ?

最小生成树模板题,因为如果有n个村庄的话,若是能畅通,定有n-1条边将其联通以构成最小生成树,否则不畅通。

#include <stdio.h>
#include <string.h>
#define maxn 102

int map[maxn][maxn];
bool vis[maxn];

void Prim(int n)
{
	int len = 0, i, j, tmp, u, v, count = 0;
	vis[1] = true;
	while(count < n - 1){
		for(i = 1, tmp = -1; i <= n; ++i){
			for(j = 1; vis[i] && j <= n; ++j) //cut
				if(map[i][j] != -1 && !vis[j] && (tmp == -1 || map[i][j] < tmp)){
					tmp = map[i][j]; u = j; v = i;
				}			
		}
		if(tmp != -1){
			map[v][u] = -1;
			len += tmp; ++count;
			vis[u] = 1;
		}else break;
	}
	if(count == n - 1) printf("%d\n", len);
	else printf("?\n");
}

int main()
{
	//freopen("in.txt", "r", stdin);
	//freopen("out.txt", "w", stdout);
	int n, m, a, b, c, i;
	while(scanf("%d%d", &n, &m), n){
		memset(map, -1, sizeof(map));
		memset(vis, 0, sizeof(vis));
		for(i = 0; i < n; ++i){
			scanf("%d%d%d", &a, &b, &c);
			if(map[a][b] == -1 || c < map[a][b])
				map[a][b] = map[b][a] = c;
		}
		Prim(m);
	}
	return 0;
}

 

抱歉!评论已关闭.