首页 > 代码库 > HDU2122 Ice_cream’s world III 【最小生成树】
HDU2122 Ice_cream’s world III 【最小生成树】
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; }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。