HDU 2122 Ice_cream’s world III(最小生成树)

Ice_cream’s world III


 

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
 
 1 #include<cstdio>
 2 #include<cstring>
 3 #include<algorithm>
 4 using namespace std;
 5 
 6 int sum,m,n;
 7 int used[1005];
 8 int lowercost[1005];
 9 int edge[1005][1005];
10 const int inf=999999;
11 
12 bool prim()
13 {
14     int i,j,k;
15     used[0]=1;
16     for(i=1;i<n;i++)
17     lowercost[i]=edge[0][i];
18     for(i=0;i<n-1;i++)
19     {
20         int maxn=inf;
21         int pos;
22         for(j=0;j<n;j++)
23         {
24             if((lowercost[j]<maxn&&lowercost[j]!=-1)&&!used[j])
25             {
26                 maxn=lowercost[j];
27                 pos=j;
28             }
29         }
30         if(maxn==inf)
31         return false;
32         used[pos]=1;
33         sum+=lowercost[pos];
34         for(k=0;k<n;k++)
35         {
36             if((edge[pos][k]<lowercost[k]||lowercost[k]==-1)&&!used[k]&&k!=pos&&edge[pos][k]!=-1)
37             lowercost[k]=edge[pos][k];
38         }
39     }
40     return true;
41 }
42 
43 int main()
44 {
45     //freopen("in.txt","r",stdin);
46     int i,a,b,c;
47     while(scanf("%d%d",&n,&m)!=EOF)
48     {
49         sum=0;
50         memset(edge,-1,sizeof(edge));
51         memset(used,0,sizeof(used));
52         memset(lowercost,-1,sizeof(lowercost));
53         for(i=0;i<m;i++)
54         {
55             scanf("%d%d%d",&a,&b,&c);
56             if(edge[a][b]==-1||edge[a][b]>c)
57             edge[a][b]=edge[b][a]=c;
58         }
59         bool ans=prim();
60         if(ans)
61         printf("%d

",sum);
62         else
63         printf("impossible

");
64     }
65     return 0;
66 }
原文地址:https://www.cnblogs.com/homura/p/4717212.html