HDU 1879 继续畅通工程

本文介绍了一种使用克鲁斯卡尔算法解决最小生成树问题的方法,包括初始化、查找路径、并集操作及排序过程,通过实例演示算法实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



http://acm.hdu.edu.cn/showproblem.php?pid=1879

克鲁斯卡尔算法求解最小生成树(MST)

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>

using namespace std;

int father[110],n,m;
struct node{
    int from,to,cost;
}edge[5010];

void Init(){
    for(int i=1; i<=n; i++)
        father[i] = i;
}

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

void Union(int fx, int fy){
    father[fy] = fx;
}

bool cmp(const node &A, const node &B){
    return A.cost < B.cost;
}

int main(){
//    freopen("in.txt", "r", stdin);
    while(scanf("%d",&n) == 1 && n){
        Init();
        m = n*(n-1)/2;
        int from,to,cost,key;
        for(int i=0; i<m; i++){
            scanf("%d%d%d%d",&from,&to,&cost,&key);
            edge[i].from = from,edge[i].to = to;
            if(key) edge[i].cost = 0;
            else    edge[i].cost = cost;
        }
        sort(edge, edge+m, cmp);///将边按照权值大小排序
        int cnt = n, ans = 0;
        for(int i=0; i<m && cnt > 1; i++){///cnt = 1代表已经找到一棵最小生成树
            int fx = Find(edge[i].from), fy = Find(edge[i].to);
            if(fx != fy){
                Union(fx, fy);
                cnt--;
                ans += edge[i].cost;
            }
        }
        printf("%d\n",ans);
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值