http://acm.hdu.edu.cn/showproblem.php?pid=2122
Ice_cream’s world III
Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2634 Accepted Submission(s): 922
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
Recommend
威士忌 | We have carefully selected several similar problems for you: 2120 2121 2119 2129 2118
思路
裸的求最小生成树,模板题。
题目大意:给你一个图,求连接所有点的最短路径。
题目思路:这是一道巨简单的最小生成树模板题,由于题目中要求两个测试样例之间要空一行;
当时没有注意到。所以Debug了好久。
AC Code
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int nmax=1010;
const int mmax=10000+10;
int n,m;//点数、边数
struct Edge{
int u,v,val;//起点、终点、边权
}edge[mmax];
bool cmp(Edge a,Edge b){
return a.val<b.val; //按照边权从小到大排序,求最小生成树
}
int father[nmax];
int findFather(int u){
if(u==father[u]) return u;
else{
int f=findFather(father[u]);
father[u]=f;
return f;
}
}
void init(int n){
for(int i=0;i<=n;i++){
father[i]=i;
}
}
void Kruskal(){//返回最小生成树的边权和
init(n);
//sort(edge,edge+m,cmp);
int cnt=0;//有效合并次数
int ans=0;//最小边权和
for(int i=0;i<m;i++){//遍历m条边
int fu=findFather(edge[i].u);
int fv=findFather(edge[i].v);
if(fu!=fv){
father[fu]=fv;
ans+=edge[i].val;
cnt++;
}
if(cnt==n-1)//合并了N-1条边,已经找到了最小生成树
break;
}
if(cnt==n-1)//找到最小生成树
printf("%d\n\n",ans);
else //图不连通
printf("impossible\n\n");
}
int main(int argc, char** argv) {
while(scanf("%d %d",&n,&m)!=EOF){
/*if(n==0||m==0){
printf("impossible\n\n");
break;
}*/
memset(father,0,sizeof(father));
memset(edge,0,sizeof(edge));
init(n);
for(int i=0;i<m;i++){
scanf("%d %d %d",&edge[i].u,&edge[i].v,&edge[i].val);
}
sort(edge,edge+m,cmp);
Kruskal();
}
return 0;
}