题解 | Jungle Roads

Jungle Roads

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


#include <cstdio>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
 char father[30];
struct road {
    char a;
    char b;
    int weight;
    road(char _a, char _b, int weight1) {
        a = _a; b = _b; weight=weight1;
    }
};
void InitT(int n) {
    for (int i = 0; i < n; ++i) {
        father[i] = 'A' + i;
    }
}
int FindT(char u) {
    if (u == father[u- 'A']) { return u-'A'; }
    else {
        return FindT(father[u - 'A']);
    }
}
void UnionT(int u, int v) {
    int uroot = FindT(father[u]);
    int vroot = FindT(father[v]);
    father[vroot] = uroot + 'A';
}
bool compare(road lhs, road rhs) {
    if (lhs.weight < rhs.weight) {
        return true;
    }
    else {
        return false;
    }
}
int main() {
    int n;
    while (scanf("%d\n", &n) != EOF) {
        if (n == 0) { break; }
        InitT(n + 1);
        vector<road> p;
        for (int i = 1; i < n; ++i) {
            char arr[100] = { 0 };
            fgets(arr, 100, stdin);
            string str = arr;
            if (str[2] != '0') {
                for (int j = 3; j < str.size(); ++j) {
                    if (str[j] >= 'A' && str[j] <= 'Z') {
                        char m = str[j];
                        j = j + 2;
                        string temp = "";
                        while (str[j] >= '0' && str[j] <= '9') {temp=temp+ str[j]; ++j; }
                        int c = stod(temp);
                        road e(str[0],m,c);
                        p.push_back(e);
                    }
                }
            }
        }
        int vertex = 0;
        int total = 0;
        sort(p.begin(), p.end(), compare);
        for (int k = 0; k < p.size(); ++k) {
            if (vertex == n - 1) { break; }
            if (FindT(p[k].a) != FindT(p[k].b)) {
                ++vertex;
                UnionT(p[k].a - 'A', p[k].b - 'A');
                total += p[k].weight;
            }
        }
        printf("%d\n", total);
    }
    return 0;
}

#shit#
全部评论

相关推荐

04-25 18:13
五邑大学 Java
后来123321:大二两段实习太厉害了,我现在大二连面试都没有
点赞 评论 收藏
分享
05-26 10:24
门头沟学院 Java
qq乃乃好喝到咩噗茶:其实是对的,线上面试容易被人当野怪刷了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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