解决部分用例报错(根本原因是sort的不稳定排序)

成绩排序

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

#include <asm-generic/errno-base.h>
#include <iostream>
#include <algorithm>//sort的头文件
using namespace std;
struct Student {
    string name;
    int score;
    int rank;//rank是用来表示输入顺序的变量
};
bool compare0(Student x, Student y) {
    if (x.score == y.score) {
        return x.rank < y.rank;//返回输入顺序用以解决题设“相同成绩都按先录入排列在前的规则处理。”
    } else {
        return x.score > y.score;
    }
}
bool compare1(Student x, Student y) {
    if (x.score == y.score) {
        return x.rank < y.rank;//同上
    } else {
        return x.score < y.score;
    }
}
int main() {
    int n, f;
    Student arr[1000];//变量太小好像会溢出,这里多分配一点
    while (cin >> n >> f) {
        for (int i = 0; i < n; ++i) {
            cin >> arr[i].name >> arr[i].score;
            arr[i].rank = i;//把输入顺序录入rank
        }
        if (f == 0) {
            sort(arr, arr + n, compare0);
        } else {
            sort(arr, arr + n, compare1);
        }
        for (int j = 0; j < n; ++j) {
            std::cout << arr[j].name << " " << arr[j].score << std::endl;
        }
    }

}

全部评论

相关推荐

点赞 评论 收藏
分享
05-29 20:34
门头沟学院 C++
KarlAllen:得做好直接春招的准备。学历差的话,一是面试要求会比学历好的严格不少,二是就算面试通过了也会被排序。总之暑期和秋招对于学历差的就是及其不友好
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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