POJ-1287(裸的Krustra)

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <string>
#include <map>
using namespace std;
int V,E;

const int maxn  = 10000+10;
int father[maxn];
void Init()
{
    for(int i = 0; i < maxn ;i++)
    {
        father[i] = i;
    }
}

int Find(int x)
{
    return father[x] == x?x:father[x] = Find(father[x]);
}

bool same(int a,int b)
{
    a = Find(a);
    b = Find(b);
    return a==b;
}

void Union(int a , int b)
{
    a=Find(a);
    b=Find(b);
    if(a != b) father[a] = b;
}

struct Edge
{
    int from,to,cost;
} es[maxn];

bool cmp(const Edge &t1 , const Edge &t2)
{
    return t1.cost < t2.cost;
}

int Krustra()
{
    sort(es , es+E , cmp);
    Init();
    int sum = 0 ;
    for(int i = 0 ;i < E;i++)
    {
        Edge e = es[i];
        if(!same(e.from,e.to))
        {
            Union(e.from,e.to);
            sum += e.cost;
        }
    }
    return sum;
}
int main()
{
    while(cin >> V && V)
    {
        cin >> E;
        int from,to,cost;
        int pos = 0;
        for(int i = 0; i < E ; i++)
        {
            cin >> from >> to >> cost ;
            es[i].from = from;
            es[i].to= to;
            es[i].cost = cost;
        }
        cout << Krustra() << endl;
    }
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值