hrbust 1133 MST (最小生成树)

MST
Time Limit: 1000 MSMemory Limit: 65536 K
Total Submit: 316(117 users)Total Accepted: 160(110 users)Rating: Special Judge: No
Description

既然大家都不愿意做水题,元帅也很无奈,想了好久也不知道什么是水题,因为在元帅的眼里都是水题,他定义的非水题就是他做不出来的题。太囧了,随便弄个水的MST。

Input

测试输入包含若干测试用例。每个测试用例的第1行给出顶点数目N ( < 100 );随后的N(N-1)/2行对应村庄间的距离,每行给出一对正整数,分别是两个顶点的编号,以及此两村庄间的距离。为简单起见,村庄从1到N编号。
当N为0时,输入结束,该用例不被处理。

Output

对于每个测试用例,输出MST的最小路径总长度。

Sample Input
3
1 2 1
1 3 2
2 3 4
4
1 2 1
1 3 4
1 4 1
2 3 3
2 4 2
3 4 5
0
Sample Output
3
5
Author
最小生成树

我们需要知道每次选边的时候选择最小的边

并查集加贪心吧。。///hh练习用一下优先队列

#include<stdio.h>
#include<string.h>
#include<queue>
#include<algorithm>
using namespace std;
struct coor
{
    int x,y,d;
    friend bool operator <(coor a,coor b)
    {
        return a.d>b.d;
    }
};
int pre[10003];
priority_queue<coor>q;
int find(int x)
{
    if(x!=pre[x])
        return pre[x]=find(pre[x]);
    else return x;
}
int ans=0;
void coin(coor x)
{
    int a=find(x.x);
    int b=find(x.y);
    if(a!=b)
    {
        pre[a]=b;
       // printf(" ans:%d %d\n",a,b);
        ans+=x.d;
    }
}
void init(int n)
{
    for(int i=1; i<=n; i++)
    {
        pre[i]=i;
    }
}
int main()
{
    int n;
    while(scanf("%d",&n)==1&&n)
    {
        init(n);
        ans=0;
        int m=n*(n-1)/2;
        while(!q.empty())
            q.pop();
        coor a,b;
        for(int i=1; i<=m; i++)
        {
            scanf("%d%d%d",&a.x,&a.y,&a.d);
            q.push(a);
        }
        while(!q.empty())
        {
            b=q.top();
            coin(b);
            q.pop();
        }
        printf("%d\n",ans);
    }
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值