(HDU - 2122)Ice_cream’s world III
2017-08-24 14:16
381 查看
(HDU - 2122)Ice_cream’s world III
Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 2345 Accepted Submission(s): 830
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 10
4 0
Sample Output
10impossible
题目大意:在冰淇淋王国里,女皇想要所有城市能够连通,而且修路的花费越少越好。
思路:要所有城市连通起来,且花费越少越好,那么就是边越少越好,要使n个点连通起来至少要n-1条边,也就是一棵树;然后要是使花费越少越好,那就是这n-1条边的总权值和最小,这就变成了裸的最小生成树,套一下模板就好,我这里用的是kruskal算法。
#include<cstdio> #include<algorithm> using namespace std; const int maxn=1005; const int maxm=10005; int fa[maxn]; struct node { int u,v,w; }edge[maxm]; bool cmp(node a,node b) { return a.w<b.w; } int find(int x) { if(x==fa[x]) return x; else return fa[x]=find(fa[x]); } int main() { int n,m; while(~scanf("%d%d",&n,&m)) { for(int i=0;i<=n;i++) fa[i]=i;//初始化 for(int i=0;i<m;i++) { int u,v,w; scanf("%d%d%d",&u,&v,&w);//连边 edge[i]=(node){u,v,w}; } sort(edge,edge+m,cmp); int ans=0,cnt=0;//ans表示权值和,cnt表示边数 for(int i=0;i<m;i++) { int fu=find(edge[i].u),fv=find(edge[i].v); if(fu!=fv)//没有构成环 { fa[fu]=fv; cnt++; ans+=edge[i].w; } if(cnt==n-1) break;//已经形成树 } if(cnt==n-1) printf("%d\n\n",ans); else printf("impossible\n\n"); } return 0; }
相关文章推荐
- HDU 2122 Ice_cream’s world III 两种最小生成树算法
- HDU 2122 Ice_cream’s world III(最小生成树Kruskal)
- hdu 2122 Ice_cream’s world III
- 最小生成树 Prim 算法HDU 2122 Ice_cream’s world III
- hdu 2122 Ice_cream’s world III
- HDU 2122 Ice_cream’s world III
- Ice_cream’s world III hdu 2122 最小生成树
- hdu 2122 Ice_cream’s world III
- HDU 2122 Ice_cream’s world III
- hdu 2122:Ice_cream’s world III
- hdu 2122 Ice_cream’s world III
- hdu 2122 Ice_cream’s world III
- HDU_2122_Ice_cream’sWorldIII
- HDU 2122 Ice_cream’s world III 【最小生成树】
- hdu 2122 Ice_cream’s world III 最小生成树prim
- HDU 2122 Ice_cream’s world III
- HDU2122--Ice_cream’s world III--最小生成树--kruskal
- hdu 2122 Ice_cream’s world III(最小生成树)
- HDU - 2122 Ice_cream’s world III(Kruskal)
- hdu 2122(Ice_cream’s world III)(最小生成树,两种算法都可以)