码迷,mamicode.com
首页 > 其他好文 > 详细

HDU2122 Ice_cream’s world III 【最小生成树】

时间:2014-08-12 00:45:33      阅读:269      评论:0      收藏:0      [点我收藏+]

标签:hdu2122

Ice_cream’s world III

Time Limit: 3000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 802    Accepted Submission(s): 274


Problem Description
ice_cream’s world becomes stronger and stronger; every road is built as undirected. The queen enjoys traveling around her world; the queen’s requirement is like II problem, beautifies the roads, by which there are some ways from every city to the capital. The project’s cost should be as less as better.
 

Input
Every case have two integers N and M (N<=1000, M<=10000) meaning N cities and M roads, the cities numbered 0…N-1, following N lines, each line contain three integers S, T and C, meaning S connected with T have a road will cost C.
 

Output
If Wiskey can’t satisfy the queen’s requirement, you must be output “impossible”, otherwise, print the minimum cost in this project. After every case print one blank.
 

Sample Input
2 1 0 1 10 4 0
 

Sample Output
10 impossible

#include <stdio.h>
#include <string.h>
#include <algorithm>
#define maxn 1002
#define maxm 10002
using std::sort;

int pre[maxn], count, len;
struct Node {
	int u, v, cost;
} E[maxm];

int ufind(int k)
{
	int a = k, b;
	while(pre[k] != -1) k = pre[k];
	while(a != k) {
		b = pre[a];
		pre[a] = k;
		a = b;
	}
	return k;
}

bool cmp(Node a, Node b) {
	return a.cost < b.cost;
}

void Kruskal(int m)
{
	memset(pre, -1, sizeof(pre));
	int u, v, i; len = 0;
	for(i = 0; i < m && count > 1; ++i) {
		u = ufind(E[i].u);
		v = ufind(E[i].v);
		if(u != v) {
			len += E[i].cost;
			pre[v] = u;
			--count;
		}
	}
	if(1 == count) printf("%d\n\n", len);
	else printf("impossible\n\n");
}

int main()
{
	int n, m, i;
	while(scanf("%d%d", &n, &m) == 2) {
		count = n;
		for(i = 0; i < m; ++i)
			scanf("%d%d%d", &E[i].u, &E[i].v, &E[i].cost);
		sort(E, E + m, cmp);
		Kruskal(m);
	}
	return 0;
}


HDU2122 Ice_cream’s world III 【最小生成树】,布布扣,bubuko.com

HDU2122 Ice_cream’s world III 【最小生成树】

标签:hdu2122

原文地址:http://blog.csdn.net/chang_mu/article/details/38501547

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!