(HDU

来源:互联网 发布:js 如何弹出模态框 编辑:程序博客网 时间:2024/06/16 23:05

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

4 0

Sample Output

10

impossible

题目大意:在冰淇淋王国里,女皇想要所有城市能够连通,而且修路的花费越少越好。

思路:要所有城市连通起来,且花费越少越好,那么就是边越少越好,要使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;}
原创粉丝点击