题解 | 成绩排序

成绩排序

https://www.nowcoder.com/practice/0383714a1bb749499050d2e0610418b1

排序本身非常简单,但测试样例很刁钻。

根据示例2就知道,本题的输入并不是进行过一次就会结束的;因此需要采用持续检测输入的方法。可以将每一行的输入内容分别读取进2个数组,随后以存储成绩的数组中的数值作比较,并根据这个数值所对应的指针(在数组中的序号)对其他数组中对应的内容进行交换。

这题看上去用冒泡排序处理分数数组就可以解决了。然而,在测试用例1中有多个拥有相同分数的学生;如果仅用两个数组并不能保持输入时这些同分学生的顺序。因此,考虑开出新的存储“学号”的数组来保证排序结果的“输入顺序优先”。

#include <bits/stdc++.h>
#define _CRT_SECURE_NO_DEPRECATE

int main() {
    int caseCount, modeFlag;
    while (std::cin >> caseCount >> modeFlag) {
        std::vector<std::string> name(caseCount);
        std::vector<int> index(caseCount);
        std::vector<int> score(caseCount);
        for (int i = 0; i < caseCount; i++) {
            std::cin >> name[i] >> score[i];
            index[i] = i;
        }
        if (modeFlag) {
            //升序
            for (int i = 0; i < caseCount - 1; i++) {
                for (int j = i + 1; j < caseCount; j++) {
                    if (score[i] > score[j] || (score[i] == score[j] && index[i] > index[j])) {
                        std::swap(score[i], score[j]);
                        std::swap(name[i], name[j]);
                        std::swap(index[i], index[j]);
                    }
                }
            }
            for (int i = 0; i < caseCount; i++) {
                std::cout << name[i] << " " << score[i] << std::endl;
            }
        } else {
            //降序
            for (int i = 0; i < caseCount - 1; i++) {
                for (int j = i + 1; j < caseCount; j++) {
                    if (score[i] < score[j] || (score[i] == score[j] && index[i] > index[j])) {
                        std::swap(score[i], score[j]);
                        std::swap(name[i], name[j]);
                        std::swap(index[i], index[j]);
                    }
                }
            }
            for (int i = 0; i < caseCount; i++) {
                std::cout << name[i] << " " << score[i] << std::endl;
            }
        }
    }
    return 0;
}
牛客题库练习笔记 文章被收录于专栏

有的时候心血来潮会来做题。做题就会有笔记。

全部评论

相关推荐

代码飞升:别用口语,后端就写后端,前端就写前端,最后别光后悔
点赞 评论 收藏
分享
07-02 10:44
门头沟学院 C++
码农索隆:太实诚了,告诉hr,你能实习至少6个月
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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