题解 | #成绩排序#
成绩排序
https://www.nowcoder.com/practice/0383714a1bb749499050d2e0610418b1
#include<iostream>
#include<algorithm>
using namespace std;
//复习结构体
struct Student {
char name[100];
int score;
int order;
};
const int maxN = 10001;
//一开始这个没开够:牛客网只过了6/10
//提示: 段错误
//您的程序发生段错误,可能是数组越界,堆栈溢出(比如,递归调用层数太多)等情况引起
struct Student list[maxN];
//升序
bool Compare1(Student x, Student y) {
if (x.score == y.score) {
return x.order < y.order;
} else {
return x.score < y.score;
}
}
//降序
bool Compare0(Student x, Student y) {
if (x.score == y.score) {
return x.order < y.order;
} else {
return x.score > y.score;
}
}
//Compare函数定义规则:
//如果x,y是排序规则需要的顺序,则返回1
int main() {
int n;
int type;
while (scanf("%d", &n) != EOF) {
scanf("%d", &type);
for (int i = 0; i < n; i++) {
scanf("%s %d", &list[i].name, &list[i].score);
list[i].order = i;
}
if (type) {
sort(list, list + n, Compare1);
//可以直接用stable_sort这样得到的就是相同值保持输入顺序不变的排序结果
} else {
sort(list, list + n, Compare0);
}
for (int i = 0; i < n; i++) {
printf("%s %d\n", list[i].name, list[i].score);
}
}
//读入字符串的方法!
//https://blog.csdn.net/weixin_44123362/article/details/96730486
}
注意读入字符串的方法
https://blog.csdn.net/weixin_44123362/article/details/96730486
还是String+cin cout更方便呀!

查看4道真题和解析