码迷,mamicode.com
首页 > 其他好文 > 详细

HDU2122 Ice_cream’s world III【Kruskal】

时间:2015-01-19 23:38:08      阅读:409      评论:0      收藏:0      [点我收藏+]

标签:

Ice_cream’s world III


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

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
 
Author
Wiskey
 
Source

HDU 2007-10 Programming Contest_WarmUp


题目大意:给你N个点(编号为0~N-1),M条路,问最小生成树是多少,如果不能生成

小生成树,则输出impossible

思路:用Kruskal来做,如果最后得不到N-1条路,就输出impossible,否则就输出结果。


#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
using namespace std;

const int MAXN = 1100;
const int MAXM = 10010;
int N,M,father[MAXN];

int find(int x)
{
    if(x != father[x])
        father[x] = find(father[x]);
    return father[x];
}
struct EdgeNode
{
    int from;
    int to;
    int w;
}Edges[MAXM];

int cmp(EdgeNode a, EdgeNode b)
{
    return a.w < b.w;
}
void Kruskal()
{
    int ans = 0;
    int Count = 0;
    for(int i = 0; i < M; ++i)
    {
        int u = find(Edges[i].from);
        int v = find(Edges[i].to);
        if(u != v)
        {
            ans += Edges[i].w;
            father[v] = u;
            Count++;
            if(Count == N-1)
                break;
        }
    }
    if(Count == N-1)
        printf("%d\n\n",ans);
    else
        printf("impossible\n\n");
}
int main()
{
    while(~scanf("%d%d",&N,&M))
    {
        memset(Edges,0,sizeof(Edges));
        for(int i = 0; i <= N; ++i)
            father[i] = i;
        for(int i = 0; i < M; ++i)
        {
            scanf("%d%d%d",&Edges[i].from,&Edges[i].to,&Edges[i].w);
        }
        sort(Edges,Edges+M,cmp);
        Kruskal();
    }

    return 0;
}


HDU2122 Ice_cream’s world III【Kruskal】

标签:

原文地址:http://blog.csdn.net/lianai911/article/details/42887245

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!