Ice_cream’s world III
Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 997 Accepted Submission(s): 321
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
Author
Wiskey
Source
HDU 2007-10 Programming Contest_WarmUp
题目大意:给你N个点(编号为0~N-1),M条路,问最小生成树是多少,如果不能生成最
小生成树,则输出impossible
思路:用Kruskal来做,如果最后得不到N-1条路,就输出impossible,否则就输出结果。
#include<iostream> #include<algorithm> #include<cstdio> #include<cstring> using namespace std; const int MAXN = 1100; const int MAXM = 10010; int N,M,father[MAXN]; int find(int x) { if(x != father[x]) father[x] = find(father[x]); return father[x]; } struct EdgeNode { int from; int to; int w; }Edges[MAXM]; int cmp(EdgeNode a, EdgeNode b) { return a.w < b.w; } void Kruskal() { int ans = 0; int Count = 0; for(int i = 0; i < M; ++i) { int u = find(Edges[i].from); int v = find(Edges[i].to); if(u != v) { ans += Edges[i].w; father[v] = u; Count++; if(Count == N-1) break; } } if(Count == N-1) printf("%d\n\n",ans); else printf("impossible\n\n"); } int main() { while(~scanf("%d%d",&N,&M)) { memset(Edges,0,sizeof(Edges)); for(int i = 0; i <= N; ++i) father[i] = i; for(int i = 0; i < M; ++i) { scanf("%d%d%d",&Edges[i].from,&Edges[i].to,&Edges[i].w); } sort(Edges,Edges+M,cmp); Kruskal(); } return 0; }