HDOJ 2122 Ice_cream’s world III【Prime】&【Kruskal】

来源:互联网 发布:软件开发相关书籍 编辑:程序博客网 时间:2024/06/05 10:06

Ice_cream’s world III

Time Limit: 3000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1384    Accepted Submission(s): 465


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 10 1 104 0
 

Sample Output
10impossible
题目链接:HDOJ 2122 Ice_cream’s world III【Prime】&【Kruskal】

最小生成树    Kruskal      Prime   模板

已AC代码已:(Prime)

#include<cstdio>#include<cstring>#define INF 0x3f3f3f#define M 1010int map[M][M],vis[M],cost[M];int n,m;void Prime(){int i,j,pos,min,sum=0;for(i=0;i<n;++i)//将map的第一行存入cost {cost[i]=map[0][i];vis[i]=0;//标记 }vis[0]=1;for(i=1;i<n;++i){min=INF;pos=1;for(j=0;j<n;++j)//找出cost最小值 {if(!vis[j] && min>cost[j]){min=cost[j];pos=j;}}if(min==INF)//找不到路 {printf("impossible\n\n");return ;}vis[pos]=1;//标记已找的 sum+=min;//求和 for(j=0;j<n;++j)//更新 cost if(!vis[j] && cost[j]>map[pos][j])cost[j]=map[pos][j];}printf("%d\n\n",sum);return ;}int main(){int i,j,a,b,c;while(scanf("%d%d",&n,&m)!=EOF){memset(map,INF,sizeof(map));while(m--){scanf("%d%d%d",&a,&b,&c);if(map[a][b]>c)//取较小的值 map[a][b]=map[b][a]=c;}Prime();}return 0;}
已AC代码二:(Kruskal)

#include<cstdio>#include<cstring>#include<algorithm>#define M 1100using namespace std;struct NODE{int from,to,val;}s[M*10];int per[M];int n,m;bool cmp(NODE a,NODE b){return a.val<b.val;}void into()//初始化 {for(int i=0;i<=n;++i)per[i]=i;}int find(int x)//根节点 {return x==per[x]?x:per[x]=find(per[x]);}int join(int a,int b)//加边 {int fa=find(a);int fb=find(b);if(fa!=fb){per[fa]=fb;return 1;}elsereturn 0;}int main(){int k,i,a,b,c;while(scanf("%d%d",&n,&m)!=EOF){into();for(k=0;k<m;++k){scanf("%d%d%d",&a,&b,&c);s[k].from=a;s[k].to=b;s[k].val=c;}sort(s,s+k,cmp);int sum=0;for(i=0;i<k;++i){if(join(s[i].from,s[i].to)){sum+=s[i].val;}}int temp=0;for(i=0;i<n;++i){if(per[i]==i)temp++;if(temp==2)break;}if(temp==2)printf("impossible\n\n");elseprintf("%d\n\n",sum);}return 0;}


1 0
原创粉丝点击