题解 | #Jungle Roads#

Jungle Roads

https://www.nowcoder.com/practice/75c19b92d6b942f08989b335afbc73c3

// 求最小生成树
// 克鲁斯卡尔算法kruskal:从边集合中,从小到大筛选,若两端点不属于同一集合,加入该边
// 1.若该图已经连通,退出循环输出结果
// 2.或者循环完所有边,输出结果
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

struct Edge
{
    int from;
    int to;
    int length;
};

vector<Edge> edge;//装入所有边
int n;
//并查集算法start
const int maxn=27;
int father[maxn];
int height[maxn];
void init(int n){
    for(int i=0; i<n;i++)
    {
        father[i]=i;
        height[i]=0;
    }
}
int find(int x){
    if(x!=father[x]){
        father[x]=find(father[x]);
    }
    return father[x];
}
void Union(int x,int y){
    x=find(x);
    y=find(y);
    if(x!=y){
        if(height[x]<height[y]){
            father[x]=y;
        }
        else if(height[x]>height[y]){
            father[y]=x;
        }
        else{
            father[y]=x;
            height[x]++;
        }
    }
}
//求连通分量
int countFather(int n){
    int count=0;
    for(int i=0;i<n;i++){
        if(i==find(i))
            count++;
    }
    return count;
}
//并查集算法end

bool comp(Edge x,Edge y){
    return x.length<y.length;
}

void kruskal(int num_of_dot){
    int total=0;
    init(num_of_dot);
    for(auto x:edge){
		//两端点若不都在集合内,加入该边
        if(find(x.from)!=find(x.to)){
            Union(x.from,x.to);
            total+=x.length;
        }
        //如果已经连通,直接输出返回
        if(countFather(num_of_dot)==1){
            cout<<total<<endl;
            return;
        }
    }
    //遍历完所有的边任然不连通
    cout<<total<<endl;
    return;
}

int main(){
    while (cin>>n)
    {
        edge.clear();
        if(n==0) break;
        //输入
        for(int i=0;i<n-1;i++){
            char head,foot;
            int num,number,length;
            cin>>head>>num;
            for(int j=0;j<num;j++){
                cin>>foot>>length;
                Edge e;
                e.from=head-'A';
                e.to=foot-'A';
                e.length=length;
                edge.push_back(e);
            }
        }

        //按边长度从小到大排序
        sort(edge.begin(),edge.end(),comp);

        //克鲁斯卡尔算法
        kruskal(n);
    }
}

全部评论

相关推荐

好消息是活的像个人了,周末可以约会吃饭打游戏了坏消息是钱没了,当初来小红书就是为了钱啊哭笑不得😭
犯困嫌疑人:好事儿啊,取消大小周能有更多自己的时间,周末还能约对象玩,这不美滋滋?
投递小红书等公司6个岗位 > 小红书取消大小周
点赞 评论 收藏
分享
人生一梦:24年我投暑期实习,它以我不是女的为理由拒绝了我查看图片
点赞 评论 收藏
分享
不懂!!!:感觉你的项目描述太简单了,建议使用star描述法优化提炼一下,就是使用什么技术或方案解决了什么问题,有什么效果或成果,例如:对axios进行了二次封装,实现了请求的统一管理、错误的集中处理以及接口调用的简化,显著提高了开发效率和代码维护性,使用canvas技术实现了路线绘制功能,通过定义路径绘制函数和动态更新机制,满足了简化的导航可视化需求,提升了用户体验。像什么是使用其他组件库,基本功能描述就最好不要写到项目成果里面去了,加油
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务