题解 | #继续畅通工程#

继续畅通工程

https://www.nowcoder.com/practice/16212f7d46e44174b5505997ea998538

#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;

struct Line {
    int start;
    int end;
    int price;
    int state;

};
bool cmp(Line*& left, Line*& right) {
    if (left->state != right->state) {
        return left->state > right->state;
    } else {
        return left->price < right->price;
    }
}
int Father[100];

int Find(int a) {
    if (a != Father[a]) {
        Father[a] = Find(Father[a]);
    }
    return Father[a];
}

int main() {
    int n;
    while (cin >> n) {
        if (n == 0) {
            break;
        }
        //初始化并查集
        for (int i = 0; i <= n; i++) {
            Father[i] = i;
        }
        int weight = 0; //修路花费;
        vector<Line*> myLine;
        for (int i = 1; i <= (n * (n - 1)) / 2; ++i) {//把所有道路加入数组
            Line* node = new Line;
            cin >> node->start >> node->end >> node->price >> node->state;
            myLine.push_back(node);
        }
        //排序
        sort(myLine.begin(), myLine.end(), cmp);
        //查找最优路线
        for (vector<Line*>::iterator it = myLine.begin(); it != myLine.end(); ++it) {
            int start = Find((*it)->start);
            int end = Find((*it)->end);
            if (start != end) {
                Father[end] = start;
                if (0 == (*it)->state) {
                    weight += (*it)->price;
                }
            }

        }
        printf("%d\n", weight);
    }
}

全部评论

相关推荐

11-02 09:49
已编辑
货拉拉_测试(实习员工)
热爱生活的仰泳鲈鱼求你们别卷了:没事楼主,有反转查看图片
点赞 评论 收藏
分享
头像
11-07 01:12
重庆大学 Java
精致的小松鼠人狠话不多:签哪了哥
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务