【华为OD机试 】 找到比自己强的人数(C++ Java JavaScript Python)

264 阅读1分钟

题目描述

给定数组[[2,1],[3 2]],每组表示师徒关系,第一个元素是第二个元素的老师,数字代表排名,现在找出比自己强的徒弟。

输入描述

输出描述

用例

输入[[2,1],[3,2]]
输出[0,1,2]
说明

输入:

第一行数据[2,1]表示排名第 2 的员工是排名第 1 员工的导师,后面的数据以此类推。

输出:

第一个元素 0 表示成绩排名第一的导师,没有徒弟考试超过他;
第二个元素 1 表示成绩排名第二的导师,有 1 个徒弟成绩超过他
第三个元素 2 表示成绩排名第三的导师,有 2 个徒弟成绩超过他

参考

华为OD机试备考攻略 以及题库目录分值说明 考点说明

C++

#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <algorithm>

using namespace std;

int main() {
    string input_str;
    getline(cin, input_str);
    vector<pair<int, int>> grade_info;

    // 去除方括号
    string temp = "";
    for (char c : input_str) {
        if (c != '[' && c != ']') {
            temp += c;
        }
    }

    // 逗号分隔
    vector<int> grades;
    while (temp.find(',') != string::npos) {
        int found = temp.find(',');
        grades.push_back(stoi(temp.substr(0, found)));
        temp = temp.substr(found + 1);
    }
    grades.push_back(stoi(temp));

    // 两两一组
    for (int i = 0; i < grades.size(); i += 2) {
        grade_info.push_back(make_pair(grades[i], grades[i + 1]));
    }

    // 遍历找关系
    map<int, int> stronger_count;
    for (int i = 0; i < grade_info.size(); i++) {
        int teacher = grade_info[i].first;
        for (int j = 0; j < grade_info.size(); j++) {
            int student = grade_info[j].second;
            if (teacher > student) {
                stronger_count[teacher]++;
                stronger_count[student];
            }
        }
    }

    // 构造输出
    string result = "[";
    for (auto it = stronger_count.begin(); it != stronger_count.end(); it++) {
        result += to_string(it->second) + ",";
    }
    if (!stronger_count.empty()) {
        result.pop_back();
    }
    result += "]";

    cout << result << endl;

    return 0;
}