题解 | #成绩排序#
成绩排序
https://www.nowcoder.com/practice/0383714a1bb749499050d2e0610418b1
#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;
struct student{
string name;
int score;
int order;
};
int desc(student stu1,student stu2){
if(stu1.score==stu2.score){
return stu1.order<stu2.order;
}
else {
} return stu1.score>stu2.score;
}
int aes(student stu1,student stu2){
if(stu1.score==stu2.score){
return stu1.order<stu2.order;
}
else{
return stu1.score<stu2.score;
}
}
int main() {
int num=0;
int selection=0;
while( cin>>num&&num!=EOF){
cin>>selection;
student *stu=new student[num];
int i=0;
int n=num;
int order=0;
while(n!=0){
string temname;
int temscore;
cin>>temname;
cin>>temscore;
stu[i].name=temname;
stu[i].score=temscore;
stu[i].order=order++;
n--;
i++;
}
if(selection==0){
sort(stu,stu+num,desc);
for(int i=0;i<num;i++){
cout<<stu[i].name<<" "<<stu[i].score<<endl;
}
}
else{
sort(stu,stu+num,aes);
for(int i=0;i<num;i++){
cout<<stu[i].name<<" "<<stu[i].score<<endl;
}
}
}
}
// 64 位输出请用 printf("%lld")
1.重写sort内置的排序算法,desc和aes
2.struct student内应该包含一个order,这个用于实现题目要求,如果成绩相等按照录入的顺序从前往后排序,所以在录入的时候,给每个学生加一个order值,依次递增。

文远知行公司福利 520人发布