POJ - 1287 最小生成树 krusal

#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
int fa[1000];
struct edge
{
    int come, to, cost;
}d[3000];
bool cmp(edge p1, edge p2)
{
    return p1.cost < p2.cost;
}
int getf(int x)
{
    if(x == fa[x])
        return x;
    return fa[x] = getf(fa[x]);
}
void init()
{
    for(int i = 0; i < 1000; i++)
        fa[i] = i;
}
void Union(int x, int y)
{
    x = getf(x);
    y = getf(y);
    if(x == y)
        return;
    fa[x] = y;
}
bool same(int x, int y)
{
    if(getf(x) == getf(y))
        return 0;
    return 1;
}
int main()
{
    int m, n;
    while(scanf("%d%d", &n, &m) == 2)
    {
        int sum = 0;
        init();
        for(int i = 0; i < m; i++)
            cin >> d[i].come >> d[i].to >> d[i].cost;
        sort(d, d + m, cmp);
        for(int i = 0; i < m; i++)
        {
            if(same(d[i].come, d[i].to))
            {
                Union(d[i].come, d[i].to);
                sum += d[i].cost;
            }
        }
        cout << sum << endl;
    }
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值