题解 | #成绩排序#

成绩排序

https://www.nowcoder.com/practice/0383714a1bb749499050d2e0610418b1?tpId=40&tqId=21333&tPage=1&rp=1&ru=/ta/kaoyan&qru=/ta/kaoyan/question-ranking

#include <iostream>
#include <cstdio>
#include "string"
#include "algorithm" //一般机试都用 库里的 sort,重点调compare交换条件
using namespace std;
typedef struct list {
    char name[10];
    int grade;
    int seq = 0;
} list;
bool compare1(list lhs, list rhs) { //用来升序的comapre
    if (lhs.grade < rhs.grade) {
        return true;
    } else if (lhs.grade == rhs.grade && lhs.seq < rhs.seq)
        return true;
    else
        return false;

}
bool compare2(list lhs, list rhs) { //用来降序的comapre
    if (lhs.grade > rhs.grade) {
        return true;
    } else if (lhs.grade == rhs.grade && lhs.seq < rhs.seq)
        return true;
    else
        return false;

}



int main() {
    int peopleNum = 0;
    int method = 0; //0是降序,1是升序

    while (scanf("%d", &peopleNum) != EOF) {
        scanf("%d", &method);
        list StuGrade[peopleNum];
        for (int i = 0; i < peopleNum; i++) {
            scanf("%s %d", &StuGrade[i].name, &StuGrade[i].grade);
            StuGrade[i].seq = i;
        }

        if (method == 1) {//升序
            sort(StuGrade, StuGrade + peopleNum, compare1);
        } else { //降序
            sort(StuGrade, StuGrade + peopleNum, compare2);
        }

        for (int i = 0; i < peopleNum; i++) {
            printf("%s %d\n", StuGrade[i].name, StuGrade[i].grade);
        }
    }
    return 0;
}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务