现在的位置: 首页 > 综合 > 正文

HDU 2122 Ice_cream’s world III 【最小生成树】

2018年01月21日 ⁄ 综合 ⁄ 共 1505字 ⁄ 字号 评论关闭

Ice_cream’s world III

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

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
 

/*题解:
    最小生成树基础题,并查集水过。 
*/

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int pre[1010];
int find(int x)
{
    return x==pre[x]?x:pre[x]=find(pre[x]);
}

int join(int x,int y)
{
    int fx=find(x),fy=find(y);
    if(fx!=fy)
    {
        pre[fx]=fy;
        return 1;
    }
    return 0;
}

struct edge
{
    int from;
    int to;
    int d;
}e[10010]; 

int cmp(edge a,edge b)
{
    return a.d<b.d;
}
int main()
{
    int n,m,s,t,i;
    while(scanf("%d %d",&n,&m)!=EOF)
    {
        memset(e,0,sizeof(e));
        memset(pre,0,sizeof(pre));
        for(i=0; i<n; i++)
             pre[i]=i;
        for(i=0; i<m; i++)
        {
            scanf("%d %d %d",&e[i].from,&e[i].to,&e[i].d); 
        }
        sort(e,e+m,cmp);
        for(i=0,s=0; i<m; i++)
        {
             if(join(e[i].from,e[i].to))
             {
                    s+=e[i].d;
             }
        }
        for(i=0,t=0; i<n; i++)
        {
            if(pre[i]==i)
                t++;
        }
        if(t==1)
            printf("%d\n",s);
        else 
            printf("impossible\n");
        printf("\n");
    }
    return 0;
}

抱歉!评论已关闭.