题解 | #还是畅通工程#

还是畅通工程

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

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

struct edge{
    int x;
    int y;
    int weight;
    edge(int x,int y,int w):x(x),y(y),weight(w){}
};

const int N = 100;
int father[N];
int height[N];

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

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

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

bool compare(edge lhs,edge rhs){
    return lhs.weight < rhs.weight;
}

int main(){
    int n,x,y,w;
    vector<edge> eV;
    while (cin>>n){
        if (n==0) break;

        Init(n);
        for (int i = 0; i < n*(n-1)/2; ++i) {
            cin>>x>>y>>w;
            eV.push_back(edge(x,y,w));
        }
        sort(eV.begin(),eV.end(), compare);
        int total = 0;
        for (int i = 0; i < n*(n-1)/2; ++i) {
            Union(eV[i].x,eV[i].y,eV[i].weight,total);
        }
        cout<<total<<endl;
    }
}

全部评论

相关推荐

11-17 11:15
门头沟学院 Java
金山办公终于发offer了,但薪资和平台都不如已有的offer打算拒了,A不了薪资,不满意直接拒了,留给需要的人嘿嘿嘿时间线:10.14线下一面&nbsp;,10.23线上二面,下午发测评,11月1日HR面,11月14日电话谈薪,11月17日直接发offer
star__plat...:好兄弟干的好啊,解气。金山第一次笔难度高的离谱,第二次简单的离谱全A了,用人部门筛选中估计最后还是要挂我,就这今早智联招聘还给我发信息让我投
offer帮选
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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