HDU - 2122 Ice_cream’s world III
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.InputEvery 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.OutputIf 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
裸的最小生成树。
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<algorithm> 5 6 using namespace std; 7 8 int f[10005]; 9 struct node 10 { 11 int u,v,w; 12 friend bool operator <(node x,node y) 13 { 14 return x.w<y.w; 15 } 16 }G[10005]; 17 18 int find(int x) 19 { 20 if(x!=f[x]) 21 return find(f[x]); 22 return x; 23 } 24 25 int main() 26 { 27 int n,m; 28 while(~scanf("%d%d",&n,&m)) 29 { 30 memset(G,0,sizeof(0)); 31 for(int i=0;i<n;i++) 32 f[i]=i; 33 for(int i=0;i<m;i++) 34 scanf("%d%d%d",&G[i].u,&G[i].v,&G[i].w); 35 sort(G,G+m); 36 int ans=0; 37 int s=0; 38 for(int i=0;i<m;i++) 39 { 40 int f1=find(G[i].u); 41 int f2=find(G[i].v); 42 if(f1!=f2) 43 { 44 f[f2]=f1; 45 ans+=G[i].w; 46 s++; 47 // cout<<G[i].u<<" "<<G[i].v<<endl; 48 } 49 if(s==n-1) 50 break; 51 } 52 //cout<<"s "<<s<<endl; 53 if(s<n-1) 54 printf("impossible\n\n"); 55 else 56 printf("%d\n\n",ans); 57 } 58 }