题解 | #还是畅通工程#

还是畅通工程

https://www.nowcoder.com/practice/d6bd75dbb36e410995f8673a6a2e2229

//最小生成树:边权和最小的一棵树
#include <iostream>
#include<algorithm>
using namespace std;

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

    bool operator<(const Edge& e)const{
        return length<e.length;
    }

};

Edge edge[5000];
int father[100];
int height[100];

void Initial()
{
    for(int i=0;i<100;i++)
    {
        father[i]=i;
        height[i]=0;
    }
}

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

void Union(int a,int b)
{
    a=Find(a);
    b=Find(b);
    if(a!=b)
    {
        if(height[a]>height[b])father[b]=a;
        else if(height[a]<height[b])father[a]=b;
        else
         {
            father[b]=a;
            height[a]++;
         }
    }
}

int Kruskal(int n,int edgenumber)
{
    int answer=0;
    for(int i=0;i<edgenumber;i++)
    {
        if(Find(edge[i].from)!=Find(edge[i].to))
        {
            Union(edge[i].from,edge[i].to);
            answer+=edge[i].length;
        }
    }
    return answer;
}

int main() {
    int n;
    while (cin >> n) { 
        if(n==0)break;
        int edgenumber=n*(n-1)/2;
       
        for(int i=0;i<edgenumber;i++)
        {
            cin>>edge[i].from>>edge[i].to>>edge[i].length;
        }
        sort(edge,edge+edgenumber);
        Initial();
        cout<<Kruskal(n,edgenumber)<<endl;
    }
}

全部评论

相关推荐

屌丝逆袭咸鱼计划:心态摆好,man,晚点找早点找到最后都是为了提升自己好进正职,努力提升自己才是最关键的😤难道说现在找不到找的太晚了就炸了可以鸡鸡了吗😤早实习晚实习不都是为了以后多积累,大四学长有的秋招进的也不妨碍有的春招进,人生就这样
点赞 评论 收藏
分享
06-17 00:26
门头沟学院 Java
程序员小白条:建议换下项目,智能 AI 旅游推荐平台:https://github.com/luoye6/vue3_tourism_frontend 智能 AI 校园二手交易平台:https://github.com/luoye6/vue3_trade_frontend GPT 智能图书馆:https://github.com/luoye6/Vue_BookManageSystem 选项目要选自己能掌握的,然后最好能自己拓展的,分布式这种尽量别去写,不然你只能背八股文了,另外实习的话要多投,尤其是学历不利的情况下,多找几段实习,最好公司title大一点的
无实习如何秋招上岸
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务