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<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
int f[1005];
struct edge{
int u;
int v;
int w;
};
int cmp(struct edge e1,struct edge e2){
return e1.w < e2.w;
}
int getf(int num){
if(f[num] == num) return f[num];
else{
f[num] = getf(f[num]);
return f[num];
}
}
int merge(int u,int v){
int t1 = getf(u);
int t2 = getf(v);
if(t1 != t2){
f[t2] = t1;
return 1;
}
return 0;
}
int main(){
int n,m;
while(~scanf("%d%d",&n,&m)){//scanf输入减少时间复杂度
struct edge e[10005];
for(int i = 0 ; i < m; i++){
scanf("%d%d%d",&e[i].u,&e[i].v,&e[i].w);
}
sort(e,e+m,cmp);
for(int i = 0; i < n; i++) f[i] = i;
int sum = 0;
for(int i = 0 ; i < m; i++){
if(merge(e[i].u,e[i].v)){
sum = sum + e[i].w;//不是必须要统计是否已经连接了n-1条道路 ,
//那只是一个剪枝,已经省略
}
}
int cnt = 0;
for(int i = 0; i < n; i++){
if(f[i] == i){//查询该图的连通分支度
cnt++;
if(cnt > 1)//若大于一,则说明生成了至少两棵树 ,即图不连通
break;
}
}
if(cnt>1) printf("impossible\n\n");
else printf("%d\n\n",sum);
}
return 0;
}