OpenJudge:丛林中的路(kruskal最小生成树)

本文详细介绍了经典的最小生成树(MST)算法,并通过一个具体的编程实例来展示如何使用Kruskal算法解决丛林中路径规划的问题。文章包含了完整的源代码实现及关键步骤解析。

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

题目描述

丛林中的路

解题思路

  • 邻接表输入
  • 经典最小生成树,MST模板题,和Hdu 1863.畅通工程 Kruskal模板一样
  • 注意在初始化代表元素的时候,是字符数组,需要int转char
  • 常用ASCII对应 A-65 a-97 0-48

代码

#include <iostream>
#include<algorithm>
#include<stdio.h>
using namespace std;
#define max 80
struct edge{
    char x,y;
    int w;
}paths[max];
char fa[max];
int cmp(edge a,edge b){
    return a.w<b.w;
}
void init(int n){//注意这里初始化的是char数组
    for(int i=0;i<n;i++){
        char a = 65+i;
        fa[a] = a;
    }
}
char find(char x){
    if(fa[x]==x)
        return x;
    else
        return fa[x]=find(fa[x]);
}
void _union(char x,char y){
    char xf = find(x);
    char yf = find(y);
    if(xf!=yf){
        fa[yf] = xf;
    }
}
int main() {
    int n;
    char a,b;
    int after,w;
    while(1){
        cin>>n;
        if(n==0) break;
        int m=0,ans = 0,count=0;
        for(int i=0;i<n-1;i++){
            cin>>a>>after;
            for(int j=0;j<after;j++){
                cin>>b>>w;
                paths[m].x = a;
                paths[m].y = b;
                paths[m++].w = w;
            }   
        }
        init(n);
        sort(paths,paths+m,cmp);
        for(int i=0;i<m;i++){
            char x=paths[i].x;
            char y=paths[i].y;
            if(find(x)!=find(y)){
                _union(x,y);
                count++;
                ans+=paths[i].w;
            }
        }
        if(count==n-1){
            cout<<ans<<endl;
        }else{
            cout<<"-1"<<count<<endl;
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值